user3860909
user3860909

Reputation: 77

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

Upvotes: 0

Views: 3962

Answers (3)

Linial
Linial

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

Fyre
Fyre

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

user3687357
user3687357

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

Related Questions