1

I think this may be related to Changing <source> with HTML5 Audio works in Chrome but not Safari

The issue I'm having is that attaching a MediaSource to an Audio element in the background tab doesn't open the MediaSource the Audio element never starts playback.

Easily reproducible with the following jsbin: http://jsbin.com/haqexirege/edit?js,console

var mediaSource = new MediaSource();
mediaSource.addEventListener('sourceopen', function (data) {
    console.log('media source opened', data);
});
console.log('script started');

setTimeout(function () {
    console.log('timeout callback executed');
    var audioElement = new Audio();
    audioElement.src = URL.createObjectURL(mediaSource);
    console.log('audio element attached to media source');
}, 5000);
  1. Open Dev tools in a separate window
  2. Click "Run" on the jsbin
  3. Open a new tab immediately so the jsbin tab is backgrounded

You'll see logs emitted in the console for every step of the code, but only when you put the tab in the foreground do you see the 'media source opened' log line.

Does anyone have a workaround for MediaSource?

Community
  • 1
  • 1
Evan Layman
  • 3,691
  • 9
  • 31
  • 48

1 Answers1

1

According to Apple:

Please know that our engineering team has determined that this issue behaves as intended based on the information provided.

A media element created in a background tab is blocked from playing by design.

Creating a separate element should be entirely unnecessary. You can either use a new SourceBuffer with the same element, or just append the next song to the end of the existing buffer.

[EDIT] I've also found some more details that I hope can help others. If you have multiple Audio elements on the page and you are swapping between them with different MediaSources, you must initialize the Audio elements and empty MediaSource while in the foreground tab:

const audio1 = new Audio();
audio1.src = URL.createObjectURL(new MediaSource());
const audio2 = new Audio();
audio2.src = URL.createObjectURL(new MediaSource());

If you don't initialize, when you try and set audio2.src = anotherMediaSource in the background, the anotherMediaSource won't ever open. However, if you initialize the Audio element to a media source in the foreground, you can continue to change the .src in the background.

Evan Layman
  • 3,691
  • 9
  • 31
  • 48