js 结合icomet实现队列播放语音

2019/08/09 JS

var arr = [];
var myAudio = new Audio(); 
myAudio.preload = true; 
myAudio.controls = true; 
var end = true;
var comet = new iComet({
       channel: 'abc',
       signUrl: 'http://127.0.0.1:8000/sign',
       subUrl: 'http://127.0.0.1:8100/sub',

       callback: function(content){	
          arr.push(content);//如队列  
       }
   });

function startvoice(){
    end = false;
    if(arr.length>0){
        console.log(arr);
        console.log(arr.length);
        myAudio.src = arr.shift();       //每次读数组最后一个元素 
        console.log(arr);
        console.log(arr.length);
        if(arr.length>=1){
            myAudio.addEventListener('ended', playEndedHandler, false);
        }else{
            myAudio.addEventListener('ended', falseToTrue, false);
        }
        myAudio.play(); 
        document.getElementById("audioBox").appendChild(myAudio); 
        myAudio.loop = false;//禁止循环,否则无法触发ended事件 
    }
};
//每隔0.5秒检查一下队列是否有值有的话播放
setInterval(function(){
  	if(end&&arr.length>0){
  		startvoice();
  	}
  },500);

function playEndedHandler(){
	console.log('playEndedHandler');
	myAudio.src = arr.shift();  
	myAudio.play(); 
	if(!arr.length){
		myAudio.removeEventListener('ended',playEndedHandler,false);//只有一个元素时解除绑定 
		myAudio.addEventListener('ended', falseToTrue, false);
	}  
	
} 
//控制播放队列的开关只有播放队列空了之后才允许再次调用startvoice
function falseToTrue(){
	end = true;
	myAudio.removeEventListener('ended', falseToTrue, false);
}

Search

    Table of Contents