Playing dynamically embedded sound object via Java

2019-03-28 09:56发布

问题:

I need to background load some WAV files for an HTML page using AJAX. I use AJAX to get the details of the WAV files, then use the embed tag, and I can confirm that the files have loaded successfully because when I set autostart to true, the files play. However, I need the files to play only when the user clicks on a button (or an event is fired). The following is my code to preload these files:

function preloadMedia() {
  for(var i = 0; i < testQuestions.length; i++)  {
  var soundEmbed = document.createElement("embed");
  soundEmbed.setAttribute("src", "/media/sounds/" + testQuestions[i].mediaFile);
  soundEmbed.setAttribute("hidden", true);
  soundEmbed.setAttribute("id", testQuestions[i].id);
  soundEmbed.setAttribute("autostart", false);
  soundEmbed.setAttribute("width", 0);
  soundEmbed.setAttribute("height", 0);
  soundEmbed.setAttribute("enablejavascript", true);
  document.body.appendChild((soundEmbed));
}

}

I use the following code to play the file (based on what sound file that user wants to play)

function soundPlay(which) {
  var sounder = document.getElementById(which);
  sounder.Play();
}

Something is wrong here, as none of the browsers I have tested on play the files using the code above. There are no errors, and the code just returns.

I would have left it at that (that is - I would have convinced the client to convert all WAV's to MP3 and use MooTools). But I realized that I could play the sound files, which were not dynamically embeded.

Thus, the same soundPlay function would work for a file embeded in the following manner:

<embed src="/media/sounds/hug_sw1.wav" id="sound2" width="0" heigh="0" autostart="false" enablejavascript="true"/>

anywhere within the HTML.

And it plays well in all the browsers.

Anyone have a clue on this? Is this some sort of undocumented security restriction in all the browsers? (Please remember that the files do get preloaded dynamically, as I can confirm by setting the autostart property to true - They all play).

Any help appreciated.

回答1:

Hmm.. perhaps, you need to wait for the embed object to load its "src" after calling preloadMedia() ?

Are you sure that the media file is loaded when you call soundPlay() ?



回答2:

i know your question got a bit old by now, but in case you still wonder...

soundEmbed.setAttribute("id", testQuestions[i].id);

you used the same id twice, yet getElementById returns only one element, or false if it doesn't find exactly one matching element.

you could try something like this:

soundEmbed.setAttribute("id", "soundEmbed_"+testQuestions[i].id);

always keep in mind that an id must be unique



回答3:

Just a tip for more compatibility: I read here that width and height need to be > 0 for Firefox on MacOS.