audiojs
audiojs copied to clipboard
How to attach a handler to "play", "pause" and "stop" events?
Hello, I would like to attach some event handlers to "play", "pause" and "stop" events. Is it possible?
Hi! Not sure if you need it anymore, took me like forever to make out how to get it working. I was adding my event listeners in $(document).ready(); but turns out that was not correct. The event listeners should be added in the audiojs.events.ready() instead, code follows:
audiojs.events.ready(function() {
var as = audiojs.create($("#main-player"));
$("audio").on('playing',function(){
console.log("Push playing");
});
//... Other magic events
});
Hope you get it working!
Well, audiojs
offers those event handlers by default. No need to use jQuery or anything else.
Just look at the docs: http://kolber.github.io/audiojs/docs/#section-8
audiojs.events.ready(function() {
var player = audiojs.create( element, {
play: function() {
// do something
},
pause: function() {
// do something else
}
});
});
Anyway, there is no stop
event in audiojs at all…
The main problem with this, is it is not a real 'events' interface - it simply allows you to customize the callbacks for particular events within audiojs. It allows you to perform custom actions, but only by overwriting the defaults. Being able to listen to events and trigger arbitrary functions (without affecting the default behaviour of audiojs) would make this event driven.
This should be added as a feature request, a-v-l is right that you can add functionality but as rtibbles states it will overwrite the default behaviors. For play/pause for example it will prevent the css classes from toggling between playing and paused.
I had already implemented this, @hdn8 - opened a PR for it from my fork in case there is more general interest.
After the audiojs.createAll(), audiojs wraps all <audio> tags into <div id="audiojs_wrapper0">...</div>. You can get that wrapper by id and then search for audio tags inside that div. Lastly, just add event listener to that audio element.
var audiowrapper0 = document.getElementById("audiojs_wrapper0");
var audio = $(audiowrapper0).find("audio");
audio[0].addEventListener('play', function(){
// do stuff
});