使用JavaScript播放/暂停MP3问题

时间:2017-04-25 10:28:20

标签: javascript html audio mp3

暂停播放当前播放的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;

    }
};

3 个答案:

答案 0 :(得分:0)

在playSong外移动var Song = new Audio(object.audio)。

每次调用该函数时,您基本上都会创建一个新音频!

当然,您需要进行更改以引用object.audio,因为对象不是全局的。

更好的方法是这样做:

<audio id="song" controls="controls">
  <source id="sourceMp3" src="" type="audio/mp3" />
  Your browser does not support the audio element.
</audio>

<p>
  <button onclick='playSong(drake)'> Play Song </button>
</p>
@TestPropertySource("classpath:application-test.properties")

参考小提琴:http://jsfiddle.net/jm6ky/2/

更新了小提琴:http://jsfiddle.net/c6jgjewg/2/

答案 1 :(得分:0)

您应该将音频对象存储在基础对象中,如下所示

if (object.song == undefined){
    object.song = new Audio(object.audio);
}

并使用object.song代替Song变量

您可以使用object.song.paused(boolean)知道歌曲是否暂停,然后重新启动歌曲。

答案 2 :(得分:0)

您应该有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()再次暂停播放。

此外,您不需要将播放状态保持在单独的变量中。我刚刚在audio元素上使用了.paused属性,如果播放器已暂停,则返回true。如果您确实需要一个单独的变量,则应将其作为新属性.isPlaying存储在drake对象中。

https://jsfiddle.net/5k38da10/