从arraybuffer的字节播放音频?

时间:2018-03-27 21:28:50

标签: html5 typescript audio

我有一个来自我用Java创建的休息端点的bufferarray,它返回一个byte []数组;所以我设法用HTTP获取数组(我正在使用Angular)现在我想在浏览器中播放音频。我做了一些研究,我找到了网络音频API,但错误是我无法解码数组。

context = new AudioContext();
    audioArray : ArrayBuffer;
    buf ;
let arrayBuffer  = new ArrayBuffer(this.audioArray.byteLength);
     let bufferView  = new Uint8Array(arrayBuffer);

    for (let i = 0; i < this.audioArray.byteLength; i++) {
        bufferView[i] = this.audioArray[i];
    }
    console.log(arrayBuffer);
     // this function should decode the array but the error occurs 
       // DOMException: Unable to decode audio data
    this.context.decodeAudioData(this.audioArray).then((buffer)=>{
        this.buf = buffer;
        this.play();
    }).catch((error)=>{
        console.log(error);
    });
    console.log(this.audioArray);


play() {
    let source = this.context.createBufferSource();
    source.buffer = this.buf;
    source.connect(this.context.destination);
    source.start(0);
}

我通过调用其余的API获取ngOnInit函数中的数组:)

 this.radioService.generateVoiceMethode().subscribe(res => {
        console.log(res);
        this.audioArray = new ArrayBuffer(res.byteLength);
        this.audioArray = res;
        console.log(this.audioArray);
    });

1 个答案:

答案 0 :(得分:0)

尽管这是一个古老的问题,但我正在分享一个对我有用的答案。将来可能对某些人有用。

async play(data: ArrayBuffer) {
    const context = new AudioContext();
    const buffer = await context.decodeAudioData(data);
    const source = context.createBufferSource();
    source.buffer = buffer;
    source.connect(context.destination);
    source.start();
  }

以上代码可在Angular 8中使用。