Skip to content

Instantly share code, notes, and snippets.

@vvasilev-
Created July 6, 2012 07:26
Show Gist options
  • Save vvasilev-/3058663 to your computer and use it in GitHub Desktop.
Save vvasilev-/3058663 to your computer and use it in GitHub Desktop.
mini audio player with Buzz.js
// constructor
var Player = function(source){
// cache vars
this.sound = new buzz.sound(source.split('.')[0], { formats: ['ogg', 'mp3'], volume: 100 });
this.$playBtn = $('.ui-page-active .jp-play');
this.$pauseBtn = $('.ui-page-active .jp-pause');
this.$rewindBtn = $('.ui-page-active .rewind');
this.$duration = $('.ui-page-active .jp-duration');
this.$seekBar = $('.ui-page-active .jp-seek-bar');
this.$playBar = $('.ui-page-active .jp-play-bar');
// bindEvents call
this.bindEvents();
};
Player.prototype = {
// bindEvents method
bindEvents: function(){
// save reference to the constructor
var self = this;
// on sound end
this.sound.bind('ended', function(){
self.$playBar.width(0);
self.$pauseBtn.hide();
self.$playBtn.show();
});
// on sound timeupdate
this.sound.bind('timeupdate', function(){
self.$playBar.width( this.getPercent() + '%' );
});
// on sound durationchage
this.sound.bind('durationchange', function(){
self.$duration.text( buzz.toTimer(this.getDuration()) );
});
// on sound pause
this.sound.bind('pause', function(){
self.$playBtn.show();
self.$pauseBtn.hide();
});
// on sound playing
this.sound.bind('playing', function(){
self.$playBtn.hide();
self.$pauseBtn.show();
});
// bind play button
this.$playBtn.on('click', function(){
self.playSound();
return false;
});
// bind pause button
this.$pauseBtn.on('click', function(){
self.pauseSound();
return false;
});
// bind seekbar
this.$seekBar.on('click', function(e){
var pos = ((e.pageX - self.$seekBar.offset().left)/self.$seekBar.width())*100;
if(pos > 98) pos = 100;
self.sound.setPercent(pos);
return false;
});
// bind rewind button
this.$rewindBtn.on('click', function(){
self.rewindSound(30);
return false;
});
}
// playSound method
,playSound: function(){
this.sound.play();
}
// pauseSound method
,pauseSound: function(){
this.sound.pause();
}
// rewindSound method
,rewindSound: function(time){
var dTime = this.sound.getTime() - 30;
// if time is negative
if(dTime < 0) dTime = 0;
this.sound.setTime(dTime);
}
// destroy method
,destroy: function(){
// unbind sound events
this.sound.stop();
this.sound.unbind('ended');
this.sound.unbind('timeupdate');
this.sound.unbind('durationchange');
this.sound.unbind('pause');
this.sound.unbind('playing');
// unbind click events
this.$playBtn.off('click');
this.$pauseBtn.off('click');
this.$rewindBtn.off('click');
this.$seekBar.off('click');
// reset play bar
this.$playBar.width(0);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment