Search code examples
javascriptjqueryhtmlfirefoxweb-audio-api

WebAudioAPI: Troubles appending JS audio object to <audio> html5 player in Firefox


I have recently made a 3D visualiser and I'm having some problems getting my audio code to work in Firefox.

I set up my AudioContext:

audioContextSetup: function () {
  try {
    Sound.audioContext = new (window.AudioContext || window.webkitAudioContext)();
  } catch(e) {
    alert('Web Audio API is not supported in this browser');
  }
},

I create an audioObject:

createAudioObject: function () {
  Sound.audio0 = new Audio();
  Sound.audio0.src = '/audio/MakeYouWanna.mp3';
  Sound.audio0.controls = true;
  Sound.audio0.autoplay = false;
  Sound.audio0.loop = true;
},

I set up my audioNodes:

setupAudioNodes: function () {
  Sound.sourceNode = Sound.audioContext.createMediaElementSource(Sound.audio0);
  Sound.analyserNode = Sound.audioContext.createAnalyser();
  Sound.analyserNode.fftSize = 1024,
  Sound.frequencyArray = new Uint8Array(Sound.analyserNode.frequencyBinCount);
  Sound.timeDomainArray = new Uint8Array(Sound.analyserNode.frequencyBinCount);
},

I connect my audioNodes:

connectAudioNodes: function () {
  Sound.sourceNode.connect(Sound.analyserNode);
  Sound.analyserNode.connect(Sound.audioContext.destination);
},

THEN, I run this magical line which works perfectly in Chrome: (note that #player is an empty div.)

$('#player').append(Sound.sourceNode.mediaElement);

But in Firefox, I'm getting no love. I have recently been made aware that mp3's don't work in Firefox (lame), but the player should still show up right?

I have a file drag and drop feature which also uses the .append() line above, and I tried a .wav file and that didnt work either.

website: http://tadx-3dsound.herokuapp.com/ Github repo: https://github.com/aldhsu/TeamDNM

Massive thanks, Xaun Lopez.


Solution

  • The problem is:

    $('#player').append(Sound.sourceNode.mediaElement);

    The MediaElementAudioSourceNode's mediaElement property has been deprecated for a while. It won't be supported in Chrome for long (or maybe it's already been removed, not sure), and has never existed in Firefox (because we started implementing the Web Audio API after it had been removed).

    You need to do the mapping yourself (simply keep an MediaElementAudioSourceNode <-> <audio> map), or simply do:

    $('#player').append(Sound.audio0);

    for your specific case.

    Also, Firefox has been supporting mp3 on all platforms for quite a while, now.