我正在尝试使用if语句进行切换播放功能。我使用.paused
方法/属性来检查<audio>
元素是否正在播放。我的问题是,即使正在播放音频,该属性也会返回true。这是我的代码:
var player = $("#player");
var playerE = $("#player")[0];
var playerE = $("#player").get(0);
var isPaused = playerE.paused;
function togglePlay() {
if (isPaused === false) {
player.trigger("pause");
} else {
player.trigger("play");
}
}
这里也是我的音频元素:
<audio id="player" src="source is added dynamically" controls="controls" preload="none"></audio>
如果您需要对其进行测试,请参阅以下内容:
var player = $("#player");
var playerE = $("#player")[0];
var playerE = $("#player").get(0);
var isPaused = playerE.paused;
function togglePlay() {
if (isPaused === false) {
player.trigger("pause");
} else {
player.trigger("play");
}
}
/** Added for testing **/
function check() {
alert(isPaused);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="player" src="http://98678871.ngrok.io/music/test.mp3" controls="controls" preload="none"></audio>
<button onclick="check()">Check isPlaying</button>
&#13;
如您所见,即使播放音频,它也会返回true。这里发生了什么?这是一个错误吗?
答案 0 :(得分:1)
参考和值之间存在差异。
如果您说var isPaused = playerE.paused;
它与说var isPaused = true;
相同。当playerE.paused发生变化时,isPaused不会改变。
因此,当您检查暂停状态时,必须使用playerE.paused。
var player = $("#player");
var playerE = $("#player")[0];
var playerE = $("#player").get(0);
var isPaused = playerE.paused;
function togglePlay() {
if (isPaused === false) {
player.trigger("pause");
} else {
player.trigger("play");
}
}
/** Added for testing **/
function check() {
alert(playerE.paused);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="player" src="http://98678871.ngrok.io/music/test.mp3" controls="controls" preload="none"></audio>
<button onclick="check()">Check isPlaying</button>
&#13;
您可以随时收听视频/音频暂停/播放的时间,并根据此更新变量。
var player = $("#player");
var playerE = $("#player")[0];
var playerE = $("#player").get(0);
var isPaused = true;
player.bind("pause", function() {
isPaused = true;
});
player.bind("play", function() {
isPaused = false;
});
/** Added for testing **/
function check() {
alert(isPaused);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="player" src="http://98678871.ngrok.io/music/test.mp3" controls="controls" preload="none"></audio>
<button onclick="check()">Check isPlaying</button>
&#13;