播放/暂停按钮将不会播放音频,它更像是播放/停止按钮

时间:2019-10-11 05:57:57

标签: javascript

因此,当前,当我按下按钮时,音频会播放并暂停,但音频不会从上次暂停的位置继续播放。可能与一次函数有关,但我只是停留在此上,因为我还很新,目前正在尝试学习javascript。

if (document.body.addEventListener) {
    document.body.addEventListener('click', yourHandler, false);
}else {
    document.body.attachEvent('onclick', yourHandler);//for IE
}

//yourHandler();
function once(fn, context) {
    var result;
    return function () {
        if (fn) {
            result = fn.apply(context || this, arguments);
            fn = null;
        } return result;
    };
}

// Usage
function canOnlyFireOnce(target) {
    console.log('Fired!');
    if (target) {
        audio.src = target.id;
    }
}

window.audio = new Audio();
audio.className = "ppbtn";
audio.autoplay = false;

function yourHandler(e) {
    window.e = e || window.event;
    window.target = e.target || e.srcElement;

    qElem = document.querySelector(".elemnts");

    canOnlyFireOnce(target);
    console.log(audio.src);

    if (target.className.match(/ppbtn/)) {
        console.log(audio.src);
        let listOfButtons = document.querySelectorAll(".ppbtn");
    for (let i = 0; i < listOfButtons.length; i++) {
        if (listOfButtons[i].id != target.id) {
            listOfButtons[i].textContent = "play";
        }
    }
    if (target.textContent == "play") {
        audio.play();
        target.textContent = "pause";
    }
    else {
        audio.pause();
        target.textContent = "play";

        }
    }
}

1 个答案:

答案 0 :(得分:2)

您正在重新设置音频的src。这也将导致currentTime被重设。

function canOnlyFireOnce(target) {
    console.log('Fired!');
    if (target) {
        audio.src = target.id; // <-- This is bad
    }
}

似乎没有理由这样做,所以请不要这么做。