HTML5音频有时候不会播放

时间:2017-06-19 11:42:18

标签: javascript html html5 html5-video html5-audio

在我的应用程序中,我正在创建10个音频对象,并将它们存储在浏览器变量中。根据场景,我将选择其中一个并将其分配给一个全局变量。然后我播放那个声音。一段时间后,我将停止并从全局变量中清除该音频。

每当我播放声音时,我都在验证readystate。我捕捉Play&暂停事件。

问题在于,有时声音听不到,但播放和播放暂停事件仍然被解雇。我无法一直重现它(它随机发生)。

如果有人遇到这类问题,请告诉我。



function Sound(){}
try
{
	if(new Audio().canPlayType("audio/wav") != "" && new Audio().canPlayType("audio/wav") != "no" ){
		Sound.extn="wav";//No I18N
	}
	else{
		Sound.extn="mp3";//No I18N
	}
}
catch (e) {
}

Sound.init=function(soundsobj)
{
	for (var tunename in soundsobj) 
	{
		var audioobj = new Audio(soundsobj[tunename]);
		audioobj.setAttribute("autobuffer", "true");
		audioobj.addEventListener('loadeddata', function() {
				Sound.cache[tunename]=this;
				});

		audioobj.addEventListener('loadedmetadata', function() {
				this.currentTime = 0;
				});
		Sound._SOUND_PLAYER.addEventListener( "play", function(){console.log(this.readyState);}, false);
		Sound._SOUND_PLAYER.addEventListener( "pause", function(){console.log(this.readyState);}, false);

	}
}

Sound.playTune=function(tunename,duration)
{

	if(Sound.cache[tunename])
	{

		var cachedsound = Sound.cache[tunename];
		if(cachedsound.readyState == 4)
		{
			cachedsound.currentTime = 0;
			Sound._SOUND_PLAYER = cachedsound;
			Sound.play(duration);
		}
		else
		{
			delete Sound.cache[tunename];
			var audioobj = new Audio(soundsobj[tunename]);
			audioobj.setAttribute("autobuffer", "true");
			audioobj.addEventListener('loadeddata', function() {
					Sound.cache[tunename]=this;
					Sound._SOUND_PLAYER = this;
					Sound.play(duration);
			});

		}
	}
}

Sound.play = function(duration)
{
	Sound._SOUND_PLAYER.loop=true;
	Sound._SOUND_PLAYER.play();
	clearTimeout(Sound.cleartimer);
	Sound.cleartimer = setTimeout(function(){Sound.stop()},duration*1000);
}

Sound.stop=function()
{
	try
	{
		if(Sound._SOUND_PLAYER)
		{
			Sound._SOUND_PLAYER.pause();
		}
		Sound._SOUND_PLAYER = undefined;
	}
	catch(e){}
}




0 个答案:

没有答案