Search code examples
javascripthtml5-audioaudio-streamingweb-audio-api

arraybuffor into audio src


I'm getting a arraybuffer from http response. The code below plays the audio just once but I want to to use audio as src for audio element!

    this.toSpeechService.getAudioFile(this.text).subscribe(res => {
       const context = new AudioContext();
       let source = context.createBufferSource();
       context.decodeAudioData(res, function(buffer) {
            source.buffer = buffer;
          }, null).then(() => {
            source.connect(context.destination);
            this.audioSrc = context.destination; // doesn't fill the audio player
            source.start(0);
       });
       console.log(res)
     });
    <audio controls="controls">
      <source [src]="audioSrc" type="audio/mp3/wav" />
       Your browser does not support the audio element.
    </audio>


Solution

  • In case you know the mime type of the data in the ArrayBuffer the following should work.

    this.toSpeechService.getAudioFile(this.text).subscribe(res => {
        const blob = new Blob([ res ], { type: THE_MIME_TYPE });
        const url = URL.createObjectURL(blob);
    
        YOUR_AUDIO_ELEMENT.src = url;
        YOUR_AUDIO_ELEMENT.load();
    });
    

    THE_MIME_TYPE is a placeholder for the actual mimeType. And YOUR_AUDIO_ELEMENT is a reference to your audio element.

    Once you don't need the object URL anymore you can release the memory by calling URL.revokeObjectURL(url).