0

This is somewhat a duplicate of this question, but I do not understand on how to use the accepted answer. Furthermore the question is quite old and maybe there is a better way available now.

My use case:

I want to test if audio in general is playing with Playwright. The audio source is not a DOM-Element, so checking media elements is not a solution.

This is how the code would get used:

const isAudioPlaying = page.evaluate(() => {
    /* Code goes here */
})

Edit: And this is how the code of the media playback looks like in its most simple form:

function createAudioPlayer() {
    const audio = new Audio()

    return {
      setSource: (src) => audio.src = src,
      play: () => audio.play,
      pause: () => audio.pause,
      resume: () => audio.resume,
    }
}

This factory just uses the default Audio constructor for the playback. It never touches the DOM like that.

Woww
  • 344
  • 2
  • 10
  • 1
    What is the audio source; can you share some code to share what you're trying to detect? The obvious solution would seem to be `const audioPlaying = navigator.mediaSession.playbackState !== 'none';` but I have no idea whether that might work in your particular use-case. – David Thomas Jun 03 '22 at 09:47
  • @DavidThomas I added a code example. Unluckily `navigator.mediaSession.playbackState` does not seem to work in this case. If there is not other way though, I will probably just add a hidden audio element to the page, just to get it working – Woww Jun 03 '22 at 09:54
  • I tested it a bit more and it does not seem that `mediaSession` provides this functionality. Instead it needs to get set programmatically manually. – Woww Jun 03 '22 at 10:18
  • What about [`mediaElement.paused` and `mediaElement.ended`](https://html.spec.whatwg.org/multipage/media.html#dom-media-paused-dev)? They can't be true if the audio is playing. So checking if both are false would mean that the media-element is playing or loading/buffering. The HTML Audio Element inherits this properties, so you can check for `!audio.ended && !audio.paused` – Christopher Jun 03 '22 at 11:13
  • @Christopher I decided to do something like that, but it only works with elements loaded into the dom (so I just added an invisible player for that). The question itself though is for getting the overall audio playback, not restricted to the dom – Woww Jun 03 '22 at 11:36

0 Answers0