Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function when <audio> is at specific time

I am currently doing some fun website, which requires audio cues (I assume that's the name?). I want the site to do something, when the song has been played for exactly X amount of time.

I can easily get the current time using element.currentTime, but I have no clue how to say: when element.currentTime == 5.2, runFunction() - If you know what I mean. Is there some kind of way this could be done? My current test code:

<----AUDIO WILL START PLAYING---->
http://jsfiddle.net/jfL4mcnh/

$("<audio id='audioElement'>").appendTo("body");
$("#audioElement").attr("src", "http://mp3ornot.com/songs/1B.mp3").attr("autoplay", "autoplay");

setInterval(function() {
    //for some reason, $("#audioElement").currentTime won't work, so we're going old fashion
    time = document.getElementById("audioElement").currentTime;
    console.log(time);
}, 1000);

Also, I forgot to say this, I cannot do a setTimeout() and hit at the exact moment I want in milliseconds, because the audio can take some extra time to load, while the actual code runs exactly when it has been "seen", if you know what I mean. So no countdown. I need to be exact here.

like image 439
MortenMoulder Avatar asked Sep 01 '26 12:09

MortenMoulder


1 Answers

If you need greater resolution than ontimeupdate provides, you can use a setInterval instead.

Live Demo (sound and alert box only!):

$("<audio id='audioElement'>").appendTo("body");
$("#audioElement").attr("src", "http://mp3ornot.com/songs/1B.mp3").attr("autoplay", "autoplay");

var triggered = false;

var ael = document.getElementById("audioElement");
var interval = setInterval(function(){
    console.log(ael.currentTime);
    if (!triggered && ael.currentTime >= 5.2) {
        triggered = true;
        alert("5.2 seconds reached");
    }
    if (ael.ended) clearInterval(interval);
}, 50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

JSFiddle Version: http://jsfiddle.net/jfL4mcnh/15/

like image 129
Maximillian Laumeister Avatar answered Sep 04 '26 01:09

Maximillian Laumeister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!