//////////////////////////////
/**
* Эмуляция аудио объекта
* @param {string} src
* @constructor
*/
var Audio = function (src) {
this._time = Audio.randomInt(1000, 4000);
this._timer = null;
this._timeStart = null;
this._events = {};
this.src = src;
var that = this;
setTimeout(function () {
that._trigger("canplay");
}, Audio.randomInt(0, 500));
};
/**
* подписка на события
* @param {string} event
* @param {function} handler
*/
Audio.prototype.addEventListener = function (event, handler) {
if (!this._events[event]) this._events[event] = [];
this._events[event].push(handler);
};
/**
* Запускаем проигрывание
*/
Audio.prototype.play = function () {
var that = this;
this._trigger("play");
this._timeStart = Date.now();
this._timer = setTimeout(function () {
that._trigger("ended")
}, this._time);
};
/**
* Ставим на паузу
*/
Audio.prototype.pause = function () {
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
this._time = Date.now() - this._timeStart;
this._timeStart = null;
}
};
/**
* Снимаем обработчики
* @param {string} event
* @param {function} handler
*/
Audio.prototype.removeEventListener = function (event, handler) {
if (this._events[event]) {
this._events[event] = this._events[event].filter(function ($handler) {
return $handler != handler;
});
}
};
/**
* Запускаем событие
* @param event
* @private
*/
Audio.prototype._trigger = function (event) {
if (this._events[event]) {
this._events[event].forEach(function (handler) {
handler.call(this);
}, this);
}
};
/**
* Генерируем целое рандомное число
* @param {number} min
* @param {number} max
* @returns {number}
*/
Audio.randomInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
/**
* Менеджер треков
* @param {string[]} tracks
* @constructor
*/
var TrackManager = function (tracks) {
this._active = 0;
this._collection = [];
this._createTracks(tracks);
};
/**
* Запускаем проигрывание треков
*/
TrackManager.prototype.play = function () {
if (this._active in this._collection) {
this._collection[this._active].play();
}
};
/**
* Создаем треки и подписываемся на события
* @param {string[]} tracks
* @private
*/
TrackManager.prototype._createTracks = function (tracks) {
tracks.forEach(function (src) {
var audio = new Audio(src), that = this;
audio.addEventListener("canplay", function () {
console.log(this.src + " canplay");
});
audio.addEventListener("play", function () {
var request = new XMLHttpRequest();
request.open("GET", this.src, true);
//console.log(request);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
audioBuffer = buffer;
var duration = audioBuffer.duration;
//console.log(audioBuffer);
startSound();
getduration();
}, function(e) {
$('#prompt').text("error loading mp3");
console.log(e);
});
};
request.send();
});
audio.addEventListener("ended", function () {
alert(this.src + " ended");
that._onEnd();
});
this._collection.push(audio);
}, this);
};
/**
* Запускаем следующий трек когда заканчивается предыдущий;
* @private
*/
TrackManager.prototype._onEnd = function () {
this._active++;
var request = new XMLHttpRequest();
request.open("GET", this.src, true);
//console.log(request);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
audioBuffer = buffer;
var duration = audioBuffer.duration;
//console.log(audioBuffer);
startSound();
getduration();
}, function(e) {
$('#prompt').text("error loading mp3");
console.log(e);
});
};
request.send();
};
var playlist = new Array();
var musicarray = {<?=$playlist;?>};
//console.log(musicarray.playlist.length);
var i;
//var audioURL = new array();
//var audioindex = 0;
for(i = 0; i < musicarray.playlist.length; i++)
{
//var audios = this;
//console.log(i++);
//console.log(musicarray.playlist[i].url);
playlist[i] = musicarray.playlist[i].url;
//console.log(audioURL);
//audioindex ++;
}
//console.log(playlist);
new TrackManager(playlist).play();
console.log(TrackManager);
/////////////////////////////
var playing;
function startSound() {
if (source){
source.stop(0.0);
source.disconnect();
}
// Connect audio processing graph
source = audioContext.createBufferSource();
source.connect(audioContext.destination);
source.connect(analyser);
source.buffer = audioBuffer;
source.loop = false;
source.start(0.0);
startViz();
playing = this;
return playing;
console.log(playing);
}
По вашему примеру сделал так - тут же выдает единоразово, что трек "url трека" ended и один раз он проиграл, а второй раз - нет.