Reputation: 85
I'm currently working on a mobile app in which I need a custom HTML5 audio player. Here is the basic HTML for my player:
<div data-enhance="false">
<audio id="music" preload="true">
<source src="./testfiles/track_t.wav" type="audio/wav">
<source src="./testfiles/track_t.mp3" type="audio/mpeg">
</audio>
<div id="audioplayer">
<button id="pButton" class="play"></button>
<div id="timeline">
<div id="playhead"></div>
</div>
</div>
</div>
So far I can play and pause the music just fine, however I came across a problem while trying to get the playhead to move along the timeline.
When I wanted to test the function that is used to make it move, I noticed that it didn't work. First I thought my function was wrong, but everything seemed alright, so I traced the problem back to it's root. Here is the javascript code I'm using to fetch the duration:
var dur;
$('#music').bind('canplay', function(){
dur = $('#music').duration;
alert($('#music').duration);
});
As you can see there is an alert() there, with which I noticed what the problem is. When executing this alert() it returns "undefined", meaning it's unable to fetch the duration of my audio element.
When looking online for a solution I noticed that most people with a similar problem either try to fetch the duration before the file is loaded, or are using raw javascript. Which led me to the conclusion that the jQuery selection is probably wrong. I tried a few different ways to select the duration.
$('#music').html('duration');
returns "[object Object]", and
$('#music').attr('duration');
also yielded "undefined".
This is how I ended up here, I don't know what to try anymore. The jQuery I'm using is jQuery mobile for app development. All file-paths are correct, as said, I can play and pause the music just fine. Hopefully someone can help me, thanks in advance! ^^
Upvotes: 2
Views: 2357
Reputation: 388316
You are trying to read the property of a jQuery object($('#music')
), the duration property belongs to the dom element.
Since inside the event handler this
refers(by default) to the element targetted by the handler(in this case the audio element itself), you can use this.duration
$('#music').bind('canplay', function(){
dur = this.duration;
alert(this.duration);
});
Upvotes: 2