check if audiotrack is playing getusermedia in javascript

Here's a sample code to check if an Audiotrack created with getUserMedia is playing or not using the Web Audio API in JavaScript:

index.tsx
// Get user media and create an AudioTrack
navigator.mediaDevices.getUserMedia({audio: true})
  .then(stream => {
    const ctx = new AudioContext();
    const source = ctx.createMediaStreamSource(stream);
    source.connect(ctx.destination);

    // Check if the Audiotrack is playing every 100ms
    const isPlayingInterval = setInterval(() => {
      const isPlaying = ctx.state === 'running';
      console.log('Is playing:', isPlaying);
      
      if (!isPlaying) clearInterval(isPlayingInterval);
    }, 100);
  })
  .catch(err => console.error(err));
560 chars
17 lines

This code creates an AudioContext, connects the MediaStreamSource from the user media to the destination node of the context, and then checks every 100ms if the state of the context is 'running' (which indicates that the Audiotrack is playing). If the Audiotrack is not playing anymore, the interval is stopped with clearInterval.

gistlibby LogSnag