Reputation: 77
I am trying to play an audio file that is when the button was pressed
<audio controls>
<source id="player" src="foo.mp3" type="audio/mpeg"></source>
</audio>
<button onclick="functionName()">Play</button>
When the play button pressed it has to call the function and it need to start my player , and some time i need to change the src content also when the button is pressed . Thanks in advance
Upvotes: 0
Views: 3962
Reputation: 1154
Short Explanation:
var audioElement = document.createElement('audio');
->Creates New Audio Element.
audioElement.setAttribute('src', '/path/to/src');
->Set the Source of the New Audio element
audiElement.addEventListener("load",function(){
audioElement.play();
}, true);
->Creates Event Listener for when the source changes, to re-load the Audio Element Attributes
function Play(audioElement){
audioElement.play();
}
-> A public function to play the Audio Element
<button onclick="Play()">Play</button>
->Reworked Button.
Good Luck
Upvotes: 1
Reputation: 1180
I don't know why you need external button to play a song. Its already there in the audio controls. Nevertheless
var myAudio = document.getElementById("audioId");
myAudio.play();
If you want to pause externally use
myAudio.pause()
Similarly to change the source
myAudioSource = document.getElementById("player");
myAudioSource.src = "whatever.mp3";
Hope it helps!
Upvotes: 0
Reputation:
It should be like
<script>
functionname()
{
var myVideo = document.getElementById("player");
myVideo.play();
}
</script>
and for changing src
document.getElementById("player").src="new_src";
Upvotes: 0