I am dynamically creating an audio control and attempting to show it on a form with controls. I have div on the form (I've tried it with div, td, span) and I am positive I have its id correct. I am using appendChild(audio). If I put an alert() just before the function ends, the audio control will begin playing the file. As soon as the function exits, the audio player stops and I never see the control displayed. What am I missing? It seems obvious the audio variable loses scope and is no longer valid. But why can't I appendChild it to my div, td, or span? (I am in firefox, so its the ogg that is playing)
Edit - I suppose I should mention that this is being called from
HTML:
<a onclick="CreateAudio($oggfile, $id)">Play</a>
javascript:
function CreateAudio(oggfile, id)
{
var audio = document.createElement('audio');
var source= document.createElement('source');
source.type= 'audio/ogg';
source.src= oggfile;
audio.appendChild(source);
mp3file = oggfile; // I will fix this to replace ogg extension with mp3
source= document.createElement('source');
source.type= 'audio/mpeg';
source.src= mp3file;
audio.appendChild(source);
var div = document.getElementById(id);
div.appendChild(audio);
audio.load;
audio.play();
}
The audio element you originally created loses scope when the function is finished. You'll need to access the audio element that's in the DOM.
audio.setAttribute("id", "myAudioClip")
var div = document.getElementById(id);
div.appendChild(audio);
var audioElement = document.getElementById("myAudioClip");
audioElement.load();
audioElement.play();