Streaming Audio in Browser
# support
n
Hi, I establish a websocket to listen URL successfully but I am having a hard time streaming audio to the user in browser in plain JS. I have seen people talk about this problem in previous tickets but it was never resolved. Here is my code (does work when streaming audio file in chunks) -
Copy code
const AudioStream = {
  mounted() {
    ...

    this.connectWebSocket(listenUrl);
  },

  connectWebSocket(listenUrl) {
    const ws = new WebSocket(listenUrl);
    const audioContext = new AudioContext();
    
    ws.binaryType = "arraybuffer";
        
    ws.onmessage = async (event) => {
      const data = event.data;
      if (data instanceof ArrayBuffer) {
        try {
          const audioBuffer = await audioContext.decodeAudioData(data);
          const source = audioContext.createBufferSource();
          source.buffer = audioBuffer;
          source.connect(audioContext.destination);
          source.start();
        } catch (error) {
          console.error("Error playing audio:", error);
        }
      }
    };

    this.ws = ws;
    this.audioContext = audioContext;
  },
};
I end up getting the following error message in browser console - "EncodingError: Unable to decode audio data".
a
HeyN3squik Thank you for creating the ticket! A member of our team will reach out to you shortly.
v
message has been deleted
n
@User Please help when you can 🙂
q
I've a github repo that handles web audio streaming from the listen URL. I had to use an audioworklet processor to handle the audio. https://github.com/esplanadeai/LIVE-LISTEN You could repurpose some of the code there. It's in JS.
n
You are a legend, thanks a lot! 🎊 Nice and clean code, I like it 😎