首页 > 解决方案 > 使用 Lame 将原始音频转换为 mp3

问题描述

我将文件作为 Float32Array 上传到 Fire Storage 中,但为了播放它,我必须在将其存储到 firebase 到 mp3、wav 或 ogg 之前或在我获得下载 url 之后将其转换。我选择了 1 选项,使用 Lame。

let mp3Encoder = new lamejs.Mp3Encoder(1, 44100, 128);
let in16Array = Int16Array.from(audioData); //audioData is a Float32Array containing the recorded audio buffer
var mp3Tmp = mp3Encoder.encodeBuffer(in16Array); //encode mp3

//Push encode buffer to mp3Data variable
this.mp3Data.push(mp3Tmp);

//Get end part of mp3
//mp3Tmp = mp3Encoder.flush();

//Write last data to the output data, mp3Data contains now the complete mp3Data
this.mp3Data.push(mp3Tmp);

const blob = new Blob([this.mp3Data], { type: 'audio/mp3' });

但是在 firebase 中,它不会作为 mp3 上传

const id = this.i + Math.random().toString(36).substring(2) + ".mp3" ;
this.ref = this.afStorage.ref(id);
this.task = this.ref.put(blob); //code for uploading

有什么建议我接下来应该尝试什么?

标签: audiofirebase-storageavaudioplayerangular6lame

解决方案


你可以有一个简单的音频服务:

import { Injectable } from '@angular/core';
@Injectable()
export class AudioService {
  map = new Map();
  constructor() { }
  preload(src: string): HTMLAudioElement {
    if (this.map.has(src)) {
      return this.map.get(src);
    }
    const audio = new Audio();
    audio.src = src;
    audio.load();
    this.map.set(src, audio);
    return audio;
  }
  play(src: string) {
    return this.preload(src).play();
  }
  pause(src: string) {
    return this.preload(src).pause();
  }
}

然后你只需要预加载和设置音量

this.audio = this.audioService.preload('assets/audio.mp3');
this.audio.volume = this.isMuted ? 1 : 0;

而且要快乐!玩:

this.audio.play();

推荐阅读