Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why state can be invalid in Web Audio in Safari after resume?

I have a code that plays audio files which downloads from S3. On the page user sees carousel with picture and word that he should pronounce and hear a audio with correct pronounciation. The problem is in Safari, it block auto-play of audio file on window load. I know that Safari block auto play by default and in setting Auto-Play: Stop Media with Sound is enabled. When I go to the page, Safari block autoplay of audio file and page stop to load and 'freez' and AudioContext state is 'suspended' if to call resume() on any user action click on document for example, state changes to 'running', but if i click next slide, the next function will call source.stop() to stop audio playing if audio was playing, the source is a bufferSource(AudioContext.createBufferSource()) and it throw error 'InvalidStateError' screenshot with error

Why this error occurred ? If state is in 'running' not 'suspended'. Also in coursel exist 3 button to play audio again, record audio and play recorded audio and after resume all work, but when the stop function called the error shown.

like image 397
Вадим Avatar asked Mar 06 '23 03:03

Вадим


1 Answers

If you see "InvalidStateError: The object is in an invalid state in Safari (or in other browsers with a different message) when working with AudioBufferSourceNodes it is likely because you called stop() or start() on a node that has finished playing.

Quote from MDN:

An AudioBufferSourceNode can only be played once; after each call to start(), you have to create a new node if you want to play the same sound again. Fortunately, these nodes are very inexpensive to create, and the actual AudioBuffers can be reused for multiple plays of the sound. Indeed, you can use these nodes in a "fire and forget" manner: create the node, call start() to begin playing the sound, and don't even bother to hold a reference to it. It will automatically be garbage-collected at an appropriate time, which won't be until sometime after the sound has finished playing.

like image 153
salomvary Avatar answered Mar 15 '23 14:03

salomvary