Simple sound player
An example showing how implement simple sound player on Tizen 2.3 with the possibility to preload sound and play them in sequence.
SoundPlayer = function() {
this.audio = new Audio();
this.audio.preload = 'auto';
this.audio.autoplay = true;
this.audio.addEventListener('ended', function() {
this.audio.src = '';
}.bind(this));
this.isLoading = false;
this.isPlaying = false;
this.volume = 1;
this.sounds = [];
};
SoundPlayer.prototype.setVolume = function(volume) {
this.volume = Math.max(0, Math.min(1, volume));
this.sounds.forEach(function(sound) {
sound.volume = this.volume;
}, this);
};
SoundPlayer.prototype.getVolume = function() {
return this.volume;
};
SoundPlayer.prototype.play = function(url, callback) {
return SoundPlayer.prototype.playSequence([url], callback);
};
SoundPlayer.prototype.playSequence = function(soundsUrls, callback) {
if (this.isPlaying || this.isLoading) {
return false;
}
var loaded = soundsUrls.length;
var index = 0;
var onCanPlayThroughListener = function() {
loaded--;
if (loaded <= 0) {
this.isLoading = false;
play(index);
}
}.bind(this);
var onEndedListener = function() {
index++;
if (index < soundsUrls.length) {
play(index);
} else {
this.isPlaying = false;
this.sounds = [];
if (_.isFunction(callback)) {
callback();
}
}
}.bind(this);
var load = function() {
this.isLoading = true;
soundsUrls.forEach(function(soundUrl) {
var sound = new Audio();
sound.preload = 'auto';
sound.volume = this.getVolume();
sound.addEventListener('canplaythrough', onCanPlayThroughListener);
sound.addEventListener('ended', onEndedListener);
this.sounds.push(sound);
sound.src = soundUrl;
}, this);
}.bind(this);
var play = function(index) {
this.isPlaying = true;
this.sounds[index].play();
}.bind(this);
load();
return true;
};
var sp = new SoundPlayer();
sp.playSequence([
'/sounds/first.wav',
'/sounds/second.wav'
]);