Logging audio playback actions

ASP.NET, PHP, Tutorials

If you have a website with a large number of audio files you might be interested in collecting stats like who listened to what and for how long and where they paused and started again etc. Turns out that collecting data like this and saving in the log table is easier than you would think.


In this example we will be using MySQL database and here is how our log table looks like. If you enable security in your project then the “username” field will contain the username of the current user. “current_time” column stores the position of audio file where play or pause was pressed.

CREATE TABLE `audio_log` (
  `id` int(11) NOT NULL,
  `current_time` double DEFAULT NULL,
  `date` datetime DEFAULT current_timestamp(),
  `username` varchar(50) DEFAULT NULL,
  `action` varchar(50) DEFAULT NULL,
  `file` varchar(50) DEFAULT NULL
);
ALTER TABLE `audio_log`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `audio_log`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Field with audio content needs to have ‘View as’ type Audio. The following code goes to Javascript OnLoad event of the page where Audio is played, i.e. to List or to View page.

$('audio').on("play pause",function(event) {
	send_data(event);
});

function send_data(audio_event) {
  // parsing audio attributes to get the audio file name
	var fileinfo = parse_file_props(audio_event.currentTarget.src);
	// building array with data to send to the server
  var data = {
		action:audio_event.type,
		file:fileinfo.file,
		current_time:audio_event.currentTarget.currentTime
	}
  // sending data to the server 
	$.get("",{a:"log",data:data});

}

function parse_file_props(src) {
	return src.split("?").pop().split("&").reduce(
        function(p,e){
            var a = e.split('=');
            p[ decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
            return p;
        },
        {}
   );
}

And the following code goes to the BeforeProcess event of the page with audio files.

PHP:

if( postvalue("a") === "log" ){
	$data = postvalue("data");
	$data["username"] = Security::getUserName();
	DB::Insert("audio_log",$data);
	exit();
}

C#:

if( MVCFunctions.postvalue("a") == "log" ){
	dynamic data = MVCFunctions.my_json_decode(MVCFunctions.postvalue("data"));
	data.InitAndSetArrayItem(Security.getUserName(),"username");
	DB.Insert("audio_log",data);
	MVCFunctions.Exit();
}

Leave a Reply

Your email address will not be published. Required fields are marked *