document.getElementById('s/' + currentRadio + '/' + currentSong).pause();
这当前没有暂停音频而播放效果很好
document.getElementById('s/' + currentRadio + '/' + currentSong).play();
如果我在js控制台上手动输入暂停代码,音频将停止...所以不知道最新情况。
如果我试试这个
console.log(document.getElementById('s/' + currentRadio + '/' + currentSong));
我会得到div所以一切似乎都很好。
<audio class="playSong" id="s/0/0" src="/music/Playback FM/Big Daddy Kane - Warm It Up, Kane.mp3"></audio>
音频标签位于
内<div class="radioAudio">
</div>
暂停按钮就像这样
$('#tuneRadioPause').click(function(e) {
if(currentSong !== -1 && currentPlay) {
console.log("s/" + currentRadio + "/" + currentSong)
document.getElementById('s/' + currentRadio + '/' + currentSong).pause();
currentPlay = false;
}
if(!currentPlay && currentSong !== -1) {
document.getElementById('s/' + currentRadio + '/' + currentSong).play();
currentPlay = true;
}
});
答案 0 :(得分:2)
<强>更新强>
问题是有条件的检查。两个if
都是运行的。这意味着当满足第一个条件时(... && currentPlay
)currentPlay
设置为false
并且音频暂停。
然后当第二次检查在独立(!currentPlay && ...
)之后立即运行时,currentPlay
已经 false
所以此条件也是 met然后play()
立即触发,使其看起来好像暂停不起作用。
使用这样的else
语句解决:
$('#tuneRadioPause').click(function(e) {
if(currentSong !== -1 && currentPlay) {
console.log("s/" + currentRadio + "/" + currentSong)
document.getElementById('s/' + currentRadio + '/' + currentSong).pause();
currentPlay = false;
}
else if(!currentPlay && currentSong !== -1) { // else here!!
document.getElementById('s/' + currentRadio + '/' + currentSong).play();
currentPlay = true;
}
});
我建议使用audio元素的实际状态来检查而不是未绑定的标志,例如:
$('#tuneRadioPause').click(function(e) {
if (currentSong < 0 || currentRadio < 0) return;
var audio = document.getElementById('s/' + currentRadio + '/' + currentSong);
if (null === audio || audio.readyState === audio.HAVE_NOTHING) return;
if(!audio.paused && !audio.ended) {
audio.pause();
}
else if (audio.paused) {
audio.play();
}
//currentPlay = !audio.paused; // not needed anymore, but may somewhere else?
});
var currentSong = 0, currentRadio = 0;
document.getElementById('s/' + currentRadio + '/' + currentSong).oncanplay = function() {$('#tuneRadioPause')[0].disabled = false}
$('#tuneRadioPause').click(function(e) {
if (currentSong < 0 || currentRadio < 0) return;
var audio = document.getElementById('s/' + currentRadio + '/' + currentSong);
if (null === audio || audio.readyState === audio.HAVE_NOTHING) return;
if(!audio.paused && !audio.ended) {
audio.pause();
}
else if (audio.paused) {
audio.play();
}
//currentPlay = !audio.paused; // not needed anymore, but may somewhere else?
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio preload="auto" class="playSong" id="s/0/0" src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_colibris.mp3?raw=true"></audio><br>
<button disabled id="tuneRadioPause">Play / Pause</button>
答案 1 :(得分:0)
尝试使用它:
var audio = document.getElementById("yourAudio");
function pauseAudio() {
audio.pause();
}