Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracking how many times an HTML5 audio element is played?

What is the best way to track how many times an HTML5 audio element is played?

(we can use Google Analytics too, if that is the best approach)

like image 432
fancy Avatar asked Jun 29 '11 05:06

fancy


2 Answers

HTML5 Audio elements have basic callbacks.

You can combine that with a basic event callback library like jQuery to attach these events by default:

$("audio").bind("play", function(){
_gaq.push(["_trackEvent","Audio", "play", $(this).attr('src')]);
});

You can also do similar events for tracking when people finish the audio:

$("audio").bind("ended", function(){
_gaq.push(["_trackEvent","Audio", "ended", $(this).attr('src')]);
});

This can be made more concise by combining them into a single call:

$("audio").bind("play ended", function(e){
_gaq.push(["_trackEvent","Audio", e.type, $(this).attr('src')]);
});

You can also add the events on the <audio> tag attributes as onplay and onended, but, I wouldn't recommend that approach.

like image 56
Yahel Avatar answered Nov 12 '22 13:11

Yahel


If you upgraded to Universal Analytics and are not using classic analytics, then you would use a send event not a push event: ga('send', 'event', 'Audio', e.type, $(this).attr('src')); Also, if you were just testing this on your own, make sure you didn't create a filter to filter out your own IP address.

like image 20
Sarah Powers Avatar answered Nov 12 '22 13:11

Sarah Powers