Luke Sawczak
Luke Sawczak

Reputation: 333

Prevent audio resume

I have a vanilla JS web app that plays a sound in reaction to a certain event, and the press of a button stops the sound. That all works fine.

However, I recently started using a dedicated media play/pause button on my mouse and I notice that this button resumes playback of the last sound in that tab, even after it has already been cancelled.

Can I prevent this somehow? For stopping, I'm currently using the standard solution mentioned in this answer:

sound.pause();
sound.currentTime = 0;

This is in Firefox on Windows 10.

I thought of doing preventDefault on the key event since there is no reason to play/pause these (alarm) sounds as though they were media tracks. But basic research suggests that this event is handled by the browser and is not available to JS.

Upvotes: 0

Views: 164

Answers (1)

chrisguttandin
chrisguttandin

Reputation: 9066

As far as I know this behavior is not specified anywhere. Todays browsers somehow try to "do the right thing" when the user presses a hardware button to toggle sound.

There is a the Media Session Standard which allows to customize the experience but if it's not used browsers try to look for active media elements on the page to apply the events.

At least to my knowledge the Web Audio API is so far not hooked up to any hardware keys. If your files are reasonably small it might make sense to use an AudioBufferSourceNode instead of an audio element.

Anyway a quick fix which seems to work in Firefox and Chrome is to set the currentTime to the duration instead of setting it to zero.

sound.pause();
sound.currentTime = sound.duration;

Upvotes: 1

Related Questions