如何在打开循环</audio>后进行<audio>播放

时间:2015-01-25 10:44:40

标签: javascript html5 google-chrome loops audio

我正在制作一个简单的网络音频播放器。我已经复制并粘贴了下面的HTML和JS,但是不能包含音频文件,所以要查看工作示例,请查看GitHub页面:jsejcksn.github.io/audio-player/

一切都像我想要的那样,除了我注意到一个问题,它在Chrome桌面(40.0.2214.91,在OS X上)的特定条件下无法播放。我还在Safari桌面(OS X上为8.0.2)和iOS上的Chrome上进行了测试,它在这些上运行良好。以下是重现问题的步骤:

  1. Play按钮将音频文件一直播放到最后(直至停止)
  2. 按下Loop按钮
  3. 按下Play按钮(它不会播放!)
  4. 我的JavaScript有问题吗? (这似乎比Chrome桌面中的错误更有可能,但我不确定。)

    &#13;
    &#13;
    // Variables ----------
    
    var player = document.getElementById('player');
    var btnLoop = document.getElementById('btn-loop');
    var btnReplay = document.getElementById('btn-replay');
    var btnPlayPause = document.getElementById('btn-play-pause');
    
    
    // Functions ----------
    
    function endOfAudio() {
    	btnPlayPause.innerHTML = 'Play';
    	console.log('Music stopped');
    	}
    
    function loop() {
    	if (player.loop == true) {
    		player.loop = false;
    		btnLoop.innerHTML = 'Loop';
    		console.log('Looping off');
    		}
    	else if (player.loop == false) {
    		player.loop = true;
    		btnLoop.innerHTML = 'Turn off Loop';
    		console.log('Looping on');
    		}
    	}
    
    function playPause() {
    	if (player.paused == true) {
    		player.play();
    		btnPlayPause.innerHTML = 'Pause';
    		console.log('Music playing');
    		}
    	else if (player.paused == false) {
    		player.pause();
    		btnPlayPause.innerHTML = 'Play';
    		console.log('Music paused');
    		}
    	}
    
    function replay() {
    	player.currentTime = 0;
    	player.play();
    	btnPlayPause.innerHTML = 'Pause';
    	console.log('Music playing from start');
    	}
    
    
    // EventListeners ----------
    
    btnLoop.addEventListener('click', loop);
    btnPlayPause.addEventListener('click', playPause);
    btnReplay.addEventListener('click', replay);
    player.addEventListener('ended', endOfAudio);
    &#13;
    <header>
    	<h1>Audio Player</h1>
    </header>
    
    <div id="app">
    	<audio id="player" controls preload="auto" src="audio/audio.mp3"></audio>
    
    	<button id="btn-replay">Replay</button>
    	<button id="btn-play-pause">Play</button>
    	<button id="btn-loop">Loop</button>
    </div>
    &#13;
    &#13;
    &#13;

1 个答案:

答案 0 :(得分:0)

尝试检查音频播放器的ended属性cf. here。如果在按下循环按钮之前当前播放已到达结束,您可以像重播功能一样重置currentTime,然后播放。