mystix
4/17/2013 - 10:07 AM

Ext.ux.AudioPlayer.js

Ext.define('Ext.ux.AudioPlayer', {
    extend : 'Ext.Container',
    xtype  : 'audioplayer',

    config : {
        url      : null,

        height : 40,

        layout : {
            type : 'hbox'
        },

        items : [
            {
                xtype    : 'button',
                width    : 50,
                iconCls  : 'arrow_right',
                iconMask : true
            },
            {
                xtype : 'slider',
                flex  : 1
            },
            {
                xtype  : 'audio',
                hidden : true // this is hidden by default in android
            }
        ],
        control     : {
            button : {
                tap : 'onPlayButtonTap'
            },
            slider : {
                dragstart : 'onSliderDragStart',
                drag      : 'onSliderDrag'
            }
        }
    },

    initialize      : function() {
        var me = this;

        me.callParent();

        me.down('audio').setUrl(me.getUrl());
    },
    onPlayButtonTap : function(buttonCmp) {
        var me       = this,
            audioCmp = me.down('audio'),
            isPlaying;

        audioCmp.toggle();
        isPlaying = audioCmp.isPlaying();

        buttonCmp.setIconCls(isPlaying ? 'delete' : 'arrow_right');
    },
    onAudioTimeUpdate : function(audioCmp, time) {
        var duration = audioCmp.element.dom.childNodes[0].duration;

        this.down('slider').setValue((time / duration) * 100);
    },

    onSliderDrag : function(slider, thumb, value) {
        var audioCmp = this.down('audio'),
            duration = audioCmp.element.dom.childNodes[0].duration;

        value = value[0];

        audioCmp.setCurrentTime((value / 100) * duration);
        audioCmp.play();
    },
    onSliderDragStart : function() {
        this.down('audio').pause();
    }
});

// Usage example
Ext.application({
    launch : function() {
        var extension = Ext.os.is('iOS') ? 'mp3' : 'ogg';

        Ext.Viewport.add({
            xtype : 'audioplayer',
            style : 'margin-top: 10px;',
            url   : 'toughmodus.' + extension
        });
    }
});