I have the following html and script to play/pause an audio by clicking a button.
<audio id="testAudio" hidden src="sample.mp3" type="audio/mpeg">
</audio>
<button id="playAudio">Play</button>
<script>
document.getElementById("playAudio").addEventListener("click", function(){
var audio = document.getElementById('testAudio');
if(this.className == 'is-playing'){
this.className = "";
this.innerHTML = "Play"
audio.pause();
}else{
this.className = "is-playing";
this.innerHTML = "Pause";
audio.play();
}
});
</script>
I need to edit it in such a way as to play multiple mp3 files one by one in a defined order and stop only when the last audio has played.
I just don't know how to make that work. Can anyone help?
You can register an event handler for the audio tag, that first when the current file has finished;
document.getElementById("testAudio").addEventListener("ended",function(e) {
// Play next track
});
If you have a list of tracks to play in an array, then simply play the next one after the current track has finished. Using the setTimeout function you can put in a delay between the tracks. A simple example is as follows;
<script>
var playlist= [
'https://api.twilio.com/cowbell.mp3',
'https://demo.twilio.com/hellomonkey/monkey.mp3'
];
var currentTrackIndex = 0;
var delayBetweenTracks = 2000;
document.getElementById("playAudio").addEventListener("click", function(){
var audio = document.getElementById('testAudio');
if(this.className == 'is-playing'){
this.className = "";
this.innerHTML = "Play"
audio.pause();
}else{
this.className = "is-playing";
this.innerHTML = "Pause";
audio.play();
}
});
document.getElementById("testAudio").addEventListener("ended",function(e) {
var audio = document.getElementById('testAudio');
setTimeout(function() {
currentTrackIndex++;
if (currentTrackIndex < playlist.length) {
audio.src = playlist[currentTrackIndex];
audio.play();
}
}, delayBetweenTracks);
});
</script>
Note that cowbell track is 52 seconds long, so if your testing the above (for your own sanity) set the controls property to the audio tag so you can skip through most of it.
So i had this working at one point eventually i broke it and now i need to get it working again.
I want for when you press the PLAY button the video will start playing. and the PLAY button will change it text to say PAUSE. Then when you click it again the video will pause.
HTML:
<video id="myVideo" width="1024" height="576">
<source src="myaddiction.mp4" type="video/mp4">
<source src="myaddiction.mp4.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<button id="button" onclick="playPause(); ">PLAY</button>
SCRIPT:
var vid = document.getElementById("myVideo");
function playPause() {
vid.play();
}
function playPause() {
vid.pause();
}
function playPause() {
var change = document.getElementById("button");
if (change.innerHTML == "PLAY") {
change.innerHTML = "PAUSE";
} else {
change.innerHTML = "PLAY";
}
}
Here is also a fiddle with everything in it. If you know how to get a video working in it that'd be cool if you'd add it. Thanks!
https://jsfiddle.net/wb83hydn/
**EDIT: currently the problem is the video wont play when the button is pressed. The button changes text but the video does nothing.
You are defining your playPause function 3 separate times. You are likely to get some unexpected results. That is, if the interpreter doesn't error out completely. You will be better served with just creating one function, and use a global variable to handle the tracking of the play/pause state. Something like this:
var vid = document.getElementById("myVideo");
var isPlaying = false;
function playPause() {
var change = document.getElementById("button");
if (isPlaying) {
vid.pause();
change.innerHTML = "PLAY";
} else {
vid.play();
change.innerHTML = "PAUSE";
}
isPlaying = !isPlaying;
}
Change your javascript to this to make it work.
You'll need to make sure the DOM is loaded first by using window.onLoad or putting the JS at the end of the HTML file.
I updated the JSFiddle, but you'll need a valid online video file to make it work.
var vid = document.getElementById("myVideo");
function play() {
vid.play();
}
function pause() {
vid.pause();
}
function playPause() {
var change = document.getElementById("button");
if (change.innerHTML == "PLAY") {
change.innerHTML = "PAUSE";
play();
} else {
change.innerHTML = "PLAY";
pause();
}
}
https://jsfiddle.net/wb83hydn/3/
Play and pause video by the same button
document.getElementById("play").onclick = function() {
if(document.getElementById("video").paused){
document.getElementById("video").play();
this.innerHTML ="Pause";
}else{
document.getElementById("video").pause();
this.innerHTML = "Play";
}
}
I want videos to play/pause when you click on them. Firefox has this behaviour by default. Chrome does not. The simple solution I came up with was setting a click event with jQuery.
var video = $('#myVideo');
var videoDomObj = video.get(0);
//click event for the video itself
video.on('click', function(e){
//when video is clicked it should be paused when playing and vise versa
if (videoDomObj.paused){
videoDomObj.play();
} else{
videoDomObj.pause();
}
});
jsfiddle
This will work in IE and Chrome. However, this will result in a conflict in Firefox, since it will instantly call the default event afterwards and will not play the video at all. e.preventDefault() fixes this problem, but will break all the other controls in Firefox. While they still work, they will play/pause the video. Is there an easy solution for this?
In fact the raw code worked like a charm:
document.getElementById('myVideo').onclick = function(e) {
e.preventDefault();
if (this.paused){
this.play();
} else{
this.pause();
}
}
The jQuery equivalent should be:
jQuery('#myVideo').on('click', function(e) {
e.preventDefault();
if (this.paused){
this.play();
} else{
this.pause();
}
});
But as you said that breaks the video controlls, desired and simplest solution for this could be selecting a parent element (or adding a container, if required):
var video = document.getElementById('myVideo');
video.parentElement.onclick = function(e) {
if (video.paused){
video.play();
} else{
video.pause();
}
}
jQuery:
var $video = jQuery('#myVideo'), video = $video.get(0);
$video.parent().on('click', function(e) {
if (video.paused){
video.play();
} else{
video.pause();
}
});
The only solution I found was to detect the browser for this special case, since the problem only occurs in firefox and it has this feature by default anyway.
jsfiddle
//jQuery video element
var video = $('#myVideo');
//DOM element for HTML5 media events
var videoDomObj = video.get(0);
//detect if firefox
var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
//only bind click event if not firefox to prevent broken controls - firefox pauses/plays videos on click by default anyway
if (!is_firefox){
video.on('click', function(e){
//when video is clicked it should be paused when playing and vise versa
if (videoDomObj.paused){
videoDomObj.play();
} else{
videoDomObj.pause();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="myVideo" width="100%" controls>
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
I am having trouble getting the onended function to work with my HTML video. It doesnt have to be onended but basically I want a series of things to happen when the video has ended.
Code is as follows:
<script language="JavaScript" type="text/javascript">
window.onload = playVideo;
function playVideo()
{
var video = document.getElementById("video");
var message = document.getElementById("videoinfo");
var button = document.getElementById("playpause");
button.onclick = function()
{
if (video.paused)
{
video.play();
button.innerHTML = "Pause";
message.value = "The video is playing, click the Pause button to pause the video.";
}
else
{
video.pause();
button.inerHTML = "Play";
message.value = "The video is paused, click the Play button to play the video.";
}
video.onended = function(e)
{
button.innerHTML = "Play";
message.value = "The video has ended, click Play to restart the video."
}
}
}
</script>
<button type="button" id="playpause" onclick="playVideo()">Play</button>
<br>
<video id="video" width="320" height="240">
<source src="Video/movie.mp4" type="video/mp4">
<source src="Video/movie.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<br />
<textarea id="videoinfo" cols="90">
Click the Play button to start the video.
</textarea>
Thanks for the help
EDIT: I cannot post my own answer for 8 hours with 10 or less reputation, so I have to edit:
After 2 days of trying to get this to work, I post a question on here so I can figure it out. Less than 10 mins later I manage to get it to work.
I used an onEnded function in the <video> tag and linked that to a javascript function called videoEnded().
See below:
<script language="JavaScript" type="text/javascript">
function playVideo()
{
var video = document.getElementById("video");
var message = document.getElementById("videoinfo");
var button = document.getElementById("playpause");
button.onclick = function()
{
if (video.paused)
{
video.play();
button.innerHTML = "Pause";
message.value = "The video is playing, click the Pause button to pause the video.";
}
else
{
video.pause();
button.inerHTML = "Play";
message.value = "The video is paused, click the Play button to play the video.";
}
}
}
function videoEnded()
{
var message = document.getElementById("videoinfo");
var button = document.getElementById("playpause");
button.innerHTML = "Play";
message.value = "The video has ended, click Play to restart the video.";
}
</script>
Hope this can help someone else out. I have searched for days looking for an answer and nothing would work.
Thanks
if(Video.ended)
// Code when video ends.
EDIT: sorry for don't give any other explanation, but, have you tried by using .addEventListener method instead? and in which Browser do you develop / debug?
This question already has answers here:
How to tell if a <video> element is currently playing?
(7 answers)
Closed 1 year ago.
I've looked through a couple of questions to find out if an HTML5 element is playing, but can't find the answer. I've looked at the W3 documentation and it has an event named "playing" but I can't seem to get it to work.
This is my current code:
var stream = document.getElementsByTagName('video');
function pauseStream() {
if (stream.playing) {
for (var i = 0; i < stream.length; i++) {
stream[i].pause();
$("body > header").addClass("paused_note");
$(".paused_note").text("Stream Paused");
$('.paused_note').css("opacity", "1");
}
}
}
It seems to me like you could just check for !stream.paused.
Check my answer at How to tell if a <video> element is currently playing?: MediaElement does not have a property that tells if it is playing or not. But you could define a custom property for it.
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function(){
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}
})
Now you can use it on video or audio elements like this:
if(document.querySelector('video').playing){
// Do anything you want to
}
Note : This answer was given in 2011. Please check the updated documentation on HTML5 video before proceeding.
If you just want to know whether the video is paused, use the flag stream.paused.
There is no property for a video element in getting its playing status. But there is one event "playing" which will be triggered when it starts to play. An Event called "ended" is also triggered when it stops playing.
So the solution is:
Declare one variable videoStatus.
Add event handlers for different events of video.
Update videoStatus using the event handlers.
Use videoStatus to identify the status of the video.
This page will give you a better idea about video events. Play the video on this page and see how the events are triggered.
http://www.w3.org/2010/05/video/mediaevents.html
jQuery(document).on('click', 'video', function(){
if (this.paused) {
this.play();
} else {
this.pause();
}
});
Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Html5 media events</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body >
<div id="output"></div>
<video id="myVideo" width="320" height="176" controls autoplay>
<source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">
</video>
<script>
var media = document.getElementById('myVideo');
// Playing event
media.addEventListener("playing", function() {
$("#output").html("Playing event triggered");
});
// Pause event
media.addEventListener("pause", function() {
$("#output").html("Pause event triggered");
});
// Seeking event
media.addEventListener("seeking", function() {
$("#output").html("Seeking event triggered");
});
// Volume changed event
media.addEventListener("volumechange", function(e) {
$("#output").html("Volumechange event triggered");
});
</script>
</body>
</html>
Best approach:
function playPauseThisVideo(this_video_id) {
var this_video = document.getElementById(this_video_id);
if (this_video.paused) {
console.log("VIDEO IS PAUSED");
} else {
console.log("VIDEO IS PLAYING");
}
}
I encountered a similar problem where I was not able to add event listeners to the player until after it had already started playing, so #Diode's method unfortunately would not work. My solution was check if the player's "paused" property was set to true or not. This works because "paused" is set to true even before the video ever starts playing and after it ends, not just when a user has clicked "pause".
You can use 'playing' event listener =>
const video = document.querySelector('#myVideo');
video.addEventListener("playing", function () {
// Write Your Code
});
Here is what we are using at http://www.develop.com/webcasts to keep people from accidentally leaving the page while a video is playing or paused.
$(document).ready(function() {
var video = $("video#webcast_video");
if (video.length <= 0) {
return;
}
window.onbeforeunload = function () {
var htmlVideo = video[0];
if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
return null;
}
return "Leaving this page will stop your video.";
};
}
a bit example
var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
if (audio.paused) {
audio.play()
} else {
audio.pause()
}
I just looked at the link #tracevipin added (http://www.w3.org/2010/05/video/mediaevents.html), and I saw a property named "paused".
I have ust tested it and it works just fine.
This is my code - by calling the function play() the video plays or pauses and the button image is changed.
By calling the function volume() the volume is turned on/off and the button image also changes.
function play() {
var video = document.getElementById('slidevideo');
if (video.paused) {
video.play()
play_img.src = 'img/pause.png';
}
else {
video.pause()
play_img.src = 'img/play.png';
}
}
function volume() {
var video = document.getElementById('slidevideo');
var img = document.getElementById('volume_img');
if (video.volume > 0) {
video.volume = 0
volume_img.src = 'img/volume_off.png';
}
else {
video.volume = 1
volume_img.src = 'img/volume_on.png';
}
}
I just did it very simply using onpause and onplay properties of the html video tag. Create some javascript function to toggle a global variable so that the page knows the status of the video for other functions.
Javascript below:
// onPause function
function videoPause() {
videoPlaying = 0;
}
// onPause function
function videoPlay() {
videoPlaying = 1;
}
Html video tag:
<video id="mainVideo" width="660" controls onplay="videoPlay();" onpause="videoPause();" >
<source src="video/myvideo.mp4" type="video/mp4">
</video>
than you can use onclick javascript to do something depending on the status variable in this case videoPlaying.
hope this helps...
My requirement was to click on the video and pause if it was playing or play if it was paused. This worked for me.
<video id="myVideo" #elem width="320" height="176" autoplay (click)="playIfPaused(elem)">
<source src="your source" type="video/mp4">
</video>
inside app.component.ts
playIfPaused(file){
file.paused ? file.play(): file.pause();
}
var video_switch = 0;
function play() {
var media = document.getElementById('video');
if (video_switch == 0)
{
media.play();
video_switch = 1;
}
else if (video_switch == 1)
{
media.pause();
video_switch = 0;
}
}
I just added that to the media object manually
let media = document.querySelector('.my-video');
media.isplaying = false;
...
if(media.isplaying) //do something
Then just toggle it when i hit play or pause.
a bit example when playing video
let v = document.getElementById('video-plan');
v.onplay = function() {
console.log('Start video')
};