I have an audio tag in my template and I need to show currentTime of it on a button click. Please check my code below:
var myaudio = document.getElementsByTagName("audio")[0];
var cur_time = myaudio.currentTime;
$('#curPosition').val(cur_time);
But it always returns 0 as current time while the audio is playing. Do anybody have any idea on this ?
Thanks
I have an audio tag in my template and I need to show currentTime of it on a button click. Please check my code below:
var myaudio = document.getElementsByTagName("audio")[0];
var cur_time = myaudio.currentTime;
$('#curPosition').val(cur_time);
But it always returns 0 as current time while the audio is playing. Do anybody have any idea on this ?
Thanks
Share Improve this question edited Mar 19, 2014 at 10:21 laaposto 12.2k15 gold badges58 silver badges72 bronze badges asked Mar 19, 2014 at 9:45 Akhil SundarAkhil Sundar 1,3176 gold badges18 silver badges33 bronze badges 2- Provide a fiddle please,cuz i need the html as well. – Nevin Commented Mar 19, 2014 at 9:48
- Please check here with corrected typo: jsfiddle/jAdhF/1 – Akhil Sundar Commented Mar 19, 2014 at 10:00
2 Answers
Reset to default 8you can try like this
<audio id="track" src="http://upload.wikimedia/wikipedia/mons/a/a9/Tromboon-sample.ogg"
ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">
<p>Your browser does not support the audio element</p>
</audio>
<span id="tracktime">0 / 0</span>
<button onclick="document.getElementById('track').play();">Play</button>
or in javascript you can do this
<audio id='audioTrack' ontimeupdate='updateTrackTime(this);'>
Audio tag not supported in this browser</audio>
<script>
function updateTrackTime(track){
var currTimeDiv = document.getElementById('currentTime');
var durationDiv = document.getElementById('duration');
var currTime = Math.floor(track.currentTime).toString();
var duration = Math.floor(track.duration).toString();
currTimeDiv.innerHTML = formatSecondsAsTime(currTime);
if (isNaN(duration)){
durationDiv.innerHTML = '00:00';
}
else{
durationDiv.innerHTML = formatSecondsAsTime(duration);
}
}
</script>
I am currently getting time out of javascript
It is a typo. You declare var myaudio
and then you use audio.currentTime
not myaudio.currentTime
Try:
var myaudio = document.getElementsByTagName("audio")[0];
var cur_time = myaudio.currentTime;//<-----Change here
$('#curPosition').val(cur_time);
DEMO