我暂停当前正在播放的mp3时遇到问题。
例如,如果我这样运行我的函数:playSong(drake);
,它将开始从我的if语句的第一部分开始运行代码,并从“drake”对象中播放MP3并设置songValue = 2
问题是如果我第二次运行它不会暂停歌曲,但是我的console.log会显示在控制台中,所以当我第二次单击它时它肯定会运行if语句的第二部分。出于某些原因而不会暂停歌曲。
//object with mp3 audio
var drake = {
value: 3,
name: 'Energy',
artist: 'Drake',
audio: 'energy.mp3', //
img: '<img style="width: 50%; margin-right: 25%; margin-left: 25%; margin-top: 10%;" src="http://www.getrichrapping.com/wp-content/uploads/2015/08/Drake-Energy.jpg">'
};
songValue = 1;
// plays and SHOULD pause a Song
function playSong(object) {
var Song = new Audio(object.audio);
//plays the song
if (songValue == 1) {
Song.play();
songValue = 2;
// SHOULD pause the song when the functions is runned the second time
} else if (songValue == 2) {
console.log("Is it working ?"); // String to test if the "else if" gets runned
Song.pause();
songValue = 1;
}
};
最佳答案
您应该具有2个独立的功能。一种用于创建音频元素,另一种用于播放/暂停给定的音频元素。
您的问题之一是,每次调用playSong()
时,您都在创建一个全新的音频元素。
解决方案
var drake = {
value: 3,
name: 'Energy',
artist: 'Drake',
audio: 'energy.mp3', //
img: '<img style="width: 50%; margin-right: 25%; margin-left: 25%; margin-top: 10%;" src="http://www.getrichrapping.com/wp-content/uploads/2015/08/Drake-Energy.jpg">'
};
var audioElement = playSong(drake); // load song and play it
togglePlayPause(audioElement); // pause song
function playSong(object) {
var Song = new Audio(object.audio);
Song.play();
return Song;
}
function togglePlayPause(audioElement) {
if (audioElement.paused) {
audioElement.play();
} else {
audioElement.pause();
}
}
首先,使用
playSong()
函数创建音频元素并将其存储在变量中。然后,您将音频元素传递到togglePlayPause()
以切换其播放状态。在示例中,我正在播放歌曲,然后立即调用
togglePlayPause()
再次将其暂停。另外,您不需要将播放状态保持在单独的变量中。我刚刚在音频元素上使用了
.paused
属性,如果播放器已暂停,该属性将返回true。如果确实需要单独的变量,则应将其作为新属性.isPlaying
存储在drake对象中。https://jsfiddle.net/5k38da10/
关于javascript - 使用JavaScript播放/暂停MP3问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43608144/