Offer Audio file in different formats with javascript

Viewed 47

I'm using the following code to play a soundfile:

var audio = new Audio();
audio.src = 'somePath/filename.ogg';
audio.volume = 10;
audio.autoPlay = false;
audio.preLoad = true;
// ...
audio.play();

And it works well. However, some browsers may not support ogg format, so I want to add mp3 format as alternative, too. How can I do this with javascript though?

For reference, this is how it would look like in pure HTML5 when you offer multiple formats:

<audio volume="10" preload="auto">
  <source src="filename.ogg" type="audio/ogg">
  <source src="filename.mp3" type="audio/mpeg">
</audio>

So, basically instead of setting an audio.src I will need to add <source> elements to the Audio object. How do I do that though? Is there anything like a new Source() thing in javascript that I need to use here that I can somehow add to audio?

Bonus question: If the browser supports none of the offered source formats, can I somehow execute some custom code, like printing a message to the user, saying that their browser sucks? :)

1 Answers

Perhaps not exactly what you had in mind, however you could achieve this via the DOM API?

// Create audio instance with different source times by means of the DOM API
function createAudio(sourceData) {

  const audio = document.createElement('audio')
  // audio.preload = 'auto', Redundant as source children are dynamically created
  audio.volume = 10
  audio.style.display = 'none'

  // Iterate each sourceInfo of input sourceData array
  for(var sourceInfo of sourceData) {

    const source = document.createElement('source')
    source.src = sourceInfo.src
    source.type = sourceInfo.type

    // Append each source to audio instance
    audio.appendChild(source)
  }

  document.appendChild(audio)

  // Update, forgot this - thanks @Kaiido!
  audio.load()

  return audio
}

// Usage
createAudio([
  { src : 'filename.ogg', type : 'audio/ogg' },
  { src : 'filename.mp3', type : 'audio/mpeg' },
])
Related