Google Analytics(分析) - 跟踪歌曲播放

时间:2013-03-23 07:44:27

标签: javascript jquery google-analytics tracking

由于我使用Javascript播放HTML5音频,是否可以以某种方式集成一个脚本,将每首歌曲的播放请求数量和标题发送给Google Analytics?

我对谷歌分析并不太熟悉,所以我不确定这是否可行。

有没有人曾尝试过这个?

HTML:

<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="src/jquery.ubaplayer.js"></script>
<script>
jQuery(document).ready(function() { 
   jQuery.noConflict();
   jQuery(function(){
            jQuery("#ubaPlayer").ubaPlayer({
            codecs: [{name:"MP3", codec: 'audio/mpeg;'}]
            });

    });
    jQuery('a[rel=vidbox]').click(function () {

        if (jQuery("#ubaPlayer").ubaPlayer("playing") === true) {
            jQuery("#ubaPlayer").ubaPlayer("pause");
            }
        return false;
    });
})
</script>
</head>

<body>
<div id="ubaPlayer"></div>
    <ul class="controls">
        <li><a class="audioButton" href="mp3/dontthinktwice.mp3">
        Don't Think Twice (Bob Dylan)</a></li>
        <li><a class="audioButton" href="mp3/livingforthecity.mp3">
        Living for the City (Stevie Wonder)</a></li>
    </ul>
</body>

音频播放器Javascript:

(function($) {
var defaults = {
    audioButtonClass: "audioButton",
    autoPlay: null,
    codecs: [{
        name: "OGG",
        codec: 'audio/ogg; codecs="vorbis"'
    }, {
        name: "MP3",
        codec: 'audio/mpeg'
    }],
    continuous: false,
    extension: null,
    flashAudioPlayerPath: "libs/swf/player.swf",
    flashExtension: ".mp3",
    flashObjectID: "audioPlayer",
    loadingClass: "loading",
    loop: false,
    playerContainer: "player",
    playingClass: "playing",
    swfobjectPath: "libs/swfobject/swfobject.js",
    volume: 1
},
    currentTrack, isPlaying = false,
    isFlash = false,
    audio, $buttons, $tgt, $el, playTrack, resumeTrack, pauseTrack, methods = {
        play: function(element) {
            $tgt = element;
            currentTrack = _methods.getFileNameWithoutExtension($tgt.attr("href"));
            isPlaying = true;
            $tgt.addClass(defaults.loadingClass);
            $buttons.removeClass(defaults.playingClass);

            if (isFlash) {
                if (audio) {
                    _methods.removeListeners(window);
                }
                audio = document.getElementById(defaults.flashObjectID);
                _methods.addListeners(window);
                audio.playFlash(currentTrack + defaults.extension);
            } else {
                if (audio) {
                    audio.pause();
                    _methods.removeListeners(audio);
                }
                audio = new Audio("");
                _methods.addListeners(audio);
                audio.id = "audio";
                audio.loop = defaults.loop ? "loop" : "";
                audio.volume = defaults.volume;
                audio.src = currentTrack + defaults.extension;
                audio.play();
            }
        },

        pause: function() {
            if (isFlash) {
                audio.pauseFlash();
            } else {
                audio.pause();
            }

            $tgt.removeClass(defaults.playingClass);
            isPlaying = false;
        },

        resume: function() {
            if (isFlash) {
                audio.playFlash();
            } else {
                audio.play();
            }
            $tgt.addClass(defaults.playingClass);
            isPlaying = true;
        },

        playing: function() {
            return isPlaying;
        }
    },

    _methods = {
        init: function(options) {
            var types;

            //set defaults
            $.extend(defaults, options);
            $el = this;

            //listen for clicks on the controls
            $(".controls").bind("click", function(event) {
                _methods.updateTrackState(event);
                return false;
            });
            $buttons = $("." + defaults.audioButtonClass);

            types = defaults.codecs;
            for (var i = 0, ilen = types.length; i < ilen; i++) {
                var type = types[i];
                if (_methods.canPlay(type)) {
                    defaults.extension = [".", type.name.toLowerCase()].join("");
                    break;
                }
            }

            if (!defaults.extension || isFlash) {
                isFlash = true;
                defaults.extension = defaults.flashExtension;
            }

            if (isFlash) {
                $el.html("<div id='" + defaults.playerContainer + "'/>");
                $.getScript(defaults.swfobjectPath, function() {
                    swfobject.embedSWF(defaults.flashAudioPlayerPath, defaults.playerContainer, "0", "0", "9.0.0", "swf/expressInstall.swf", false, false, {
                        id: defaults.flashObjectID
                    }, _methods.swfLoaded);
                });
            } else {
                if (defaults.autoPlay) {
                    methods.play(defaults.autoPlay);
                }
            }
        },

        updateTrackState: function(evt) {
            $tgt = $(evt.target);
            if (!$tgt.hasClass("audioButton")) {
                return;
            }
            if (!audio || (audio && currentTrack !== _methods.getFileNameWithoutExtension($tgt.attr("href")))) {
                methods.play($tgt);
            } else if (!isPlaying) {
                methods.resume();
            } else {
                methods.pause();
            }
        },

        addListeners: function(elem) {
            $(elem).bind({
                "canplay": _methods.onLoaded,
                "error": _methods.onError,
                "ended": _methods.onEnded
            });
        },

        removeListeners: function(elem) {
            $(elem).unbind({
                "canplay": _methods.onLoaded,
                "error": _methods.onError,
                "ended": _methods.onEnded
            });
        },

        onLoaded: function() {
            $buttons.removeClass(defaults.loadingClass);
            $tgt.addClass(defaults.playingClass);

            audio.play();
        },

        onError: function() {
            $buttons.removeClass(defaults.loadingClass);
            if (isFlash) {
                _methods.removeListeners(window);
            } else {
                _methods.removeListeners(audio);
            }
        },

        onEnded: function() {
            isPlaying = false;
            $tgt.removeClass(defaults.playingClass);
            currentTrack = "";
            if (isFlash) {
                _methods.removeListeners(window);
            } else {
                _methods.removeListeners(audio);
            }

            if (defaults.continuous) {
                var $next = $tgt.next().length ? $tgt.next() : $(defaults.audioButtonClass).eq(0);
                methods.play($next);
            }

        },

        canPlay: function(type) {
            if (!document.createElement("audio").canPlayType) {
                return false;
            } else {
                return document.createElement("audio").canPlayType(type.codec).match(/maybe|probably/i) ? true : false;
            }
        },

        swfLoaded: function() {
            if (defaults.autoPlay) {
                setTimeout(function() {
                    methods.play(defaults.autoPlay);
                }, 500);
            }
        },

        getFileNameWithoutExtension: function(fileName) {
            //this function take a full file name and returns an extensionless file name
            //ex. entering foo.mp3 returns foo
            //ex. entering foo returns foo (no change)
            var fileNamePieces = fileName.split('.');
            fileNamePieces.pop();
            return fileNamePieces.join(".");
        }
    };

$.fn.ubaPlayer = function(method) {
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === "object" || !method) {
        return _methods.init.apply(this, arguments);
    } else {
        $.error("Method " + method + " does not exist on jquery.ubaPlayer");
    }
};})(jQuery);

2 个答案:

答案 0 :(得分:3)

是。您可以使用Google Analytics事件跟踪来跟踪任何自定义事件:

https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide

答案 1 :(得分:1)

How to Track JavaScript and Ajax Events with Google Analytics是一个相当广泛的教程,有一个mp3系统的例子。所以......是的!

Google Analytics(分析)允许您跟踪从javascript引发的自定义事件。该网站提供的一个例子是:

  

if (_gaq) _gaq.push(['_trackEvent', category, action, label, value]);   简单。该条件首先检查我们是否已包含Google Analytics   JavaScript,然后发送事件本身的详细信息。典型事件   从我们的MP3系统可能是:

_gaq.push(['_trackEvent', 'mp3system', 'search', 'good songs']);
_gaq.push(['_trackEvent', 'mp3system', 'view', 'song 1', 3456]);
_gaq.push(['_trackEvent', 'mp3system', 'download', 'song 1', 3456]);
  

对于文件下载,最简单的HTML将是:

<a href="file.mp3" onclick="_gaq.push(['_trackEvent', 'mp3system',
'download', 'file.mp3']);return true;">download</a>

以下是相应的Google文档:Event Tracking Guide