简体   繁体   中英

Playing a audio file in an onclick event

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

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

It should be like

<script>
functionname()
{
var myVideo = document.getElementById("player");
myVideo.play();
}
</script>

and for changing src

document.getElementById("player").src="new_src";

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM