slinkhi
slinkhi

Reputation: 989

capturing video source on html5 video play event

My goal is to get the src of the video playing, when the video is played.

I currently have the following code:

<!doctype html>
<html>
<head>
</head>
<body>
<video width="320" height="240" controls>
  <source src="video.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

<script type='text/javascript'>
var vid = document.getElementsByTagName('video')[0];
vid.addEventListener('play', function() {
  console.log('video source:',this.src);
}, false);
</script>
</body>
</html>

So my first problem is that this.src doesn't work; it outputs an empty string. I assume this is because the src isn't actually part of the video tag, but is in the source child tag.

I then tried to add into my function the following:

for (var p in this) {
  console.log(p, this[p]);
}

I did this to see if I could find any properties referencing it.. but I don't see anything that directly references it? So is the only way to get the source really to grab the child source nodes? If so... then...

My 2nd question, how would I determine which src attribute is actually being used to play the video? IOW if video.mp4 was actually used to play the video, I want to know that value, but if video.ogg was actually used to play the video, I want to know that value instead.

Upvotes: 1

Views: 1717

Answers (3)

Jabare Mitchell
Jabare Mitchell

Reputation: 141

The HTML5 video element already has events, so there is no need to add a listener. This is how I would do it.

var myVid = document.getElementById('videoId');    
if(myVid != null)//if possibility of no video loaded in DOM
{
    myVid.onplay = function () {
        console.log('video source: ' + myVid.currentSrc);
    };
}

Upvotes: 0

SpliFF
SpliFF

Reputation: 38976

Looks like media elements have a currentSrc property to get the chosen media file.

Upvotes: 2

emerson.marini
emerson.marini

Reputation: 9348

You can try this way:

var vid = document.getElementsByTagName('video')[0];

vid.addEventListener('play', function() {
    console.log('video source:',this.currentSrc);
}, false);

Upvotes: 4

Related Questions