107

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");
    }
  }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • I've absolutely no experience with this, but can you get information from the video tag to get the playtime timestamp? what you could do is a timer on 90ms and keep track of where in the video you are, and if the timestamp is advancing you know the video is playing... – jcolebrand Dec 22 '11 at 03:17
  • Also see: [HTML5 video tag, javascript to detect playing status?](http://stackoverflow.com/questions/6647168/html5-video-tag-javascript-to-detect-playing-status/) – Drew Gaynor Dec 22 '11 at 03:33

17 Answers17

119

It seems to me like you could just check for !stream.paused.

Samuel Cole
  • 2,005
  • 2
  • 14
  • 14
  • 23
    `!video.paused` or `video.paused === false` doesn't necessarily indicate the video is playing - it just tells you "video.play() was fired but the video could still be loading or playing". To detect if it's playing use the video.onplaying event to detect it's now loaded and playing e.g. `video.onplaying = function() { console.log('Video is now loaded and playing'); }`. This distinction may or may not be important for your needs. – Jasdeep Khalsa Jun 18 '15 at 13:03
46

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
}
Junior
  • 1,007
  • 4
  • 16
  • 26
Raees Iqbal
  • 2,160
  • 1
  • 18
  • 15
  • MDN says it should inherit from HTMLMediaElement, but I had to attach the property to HTMLVideoElement.prototype. – Marcus Pope Jul 23 '19 at 16:23
37

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:

  1. Declare one variable videoStatus.
  2. Add event handlers for different events of video.
  3. Update videoStatus using the event handlers.
  4. 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

Junior
  • 1,007
  • 4
  • 16
  • 26
Diode
  • 24,570
  • 8
  • 40
  • 51
21
jQuery(document).on('click', 'video', function(){
        if (this.paused) {
            this.play();
        } else {
            this.pause();
        }
});
geilt
  • 807
  • 8
  • 9
17

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>
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
12

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");

  }

}
Nikola Lukic
  • 4,001
  • 6
  • 44
  • 75
Junior
  • 1,007
  • 4
  • 16
  • 26
  • This is not totally correct...as when it's not playing, it could also have ended, or not even been started. technically spoken, your answer might be correct, though ;-) see https://stackoverflow.com/a/6877530/1029469 – benzkji Mar 31 '18 at 08:35
4

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".

cjroth
  • 607
  • 1
  • 6
  • 19
  • 1
    Yeah, I generally use this on an event handler for clicking the play/pause button: videoNode.paused ? videoNode.play() : videoNode.pause(); – bento Oct 21 '12 at 03:28
4

You can use 'playing' event listener =>

const video = document.querySelector('#myVideo');

video.addEventListener("playing", function () {
     // Write Your Code
});
3

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.";
    };
}
Michael Kennedy
  • 3,202
  • 2
  • 25
  • 34
2

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()
}
Preschian
  • 39
  • 3
1

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.

1

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';
  }
}
Wtower
  • 18,848
  • 11
  • 103
  • 80
Damaris
  • 21
  • 4
1

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...

JediSal
  • 65
  • 4
1

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();
}
Mesut Akcan
  • 899
  • 7
  • 19
Anish
  • 183
  • 2
  • 7
1
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;
    }
}
  • Thanks for your answer. It is best to include a brief description of how your code example answers the question, and perhaps why the original post's code does not work as wanted. Welcome to SE! – Mark Stewart Sep 04 '20 at 04:26
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.

0

a bit example when playing video

  let v = document.getElementById('video-plan');
  v.onplay = function() {
      console.log('Start video')
  };
Santiago Vasquez
  • 149
  • 1
  • 10