【问题标题】:How can I resume playing audio from web source after pausing it using HTML5 and JavaScript?使用 HTML5 和 JavaScript 暂停后,如何恢复播放来自网络源的音频?
【发布时间】:2020-03-24 22:58:15
【问题描述】:

我在tracks 数组中有一些网址,我正在通过 JavaScript 中的 HTML5 音频 API 播放这些网址。当我点击暂停时它会暂停。但是一旦暂停,当我点击播放时,音频就会从头开始播放。

HTML 规范提到了 audio.currentTime 属性,所以我尝试在一个名为 currentTime 的单独变量中跟踪它,并在再次恢复之前设置它,但这似乎并不像音频那样工作 从头开始​​。

我在试验和谷歌搜索上花费了相当长的时间,但我看不出这里出了什么问题。没有理由不从我暂停查看此代码逻辑的地方播放音频。

有其他人经历过这种情况并知道解决方法吗?

这是我的 js 文件:

$(function() {
    let trackTitle = $('#title');
    let prevBtn = $('#btn-prev');
    let playPauseBtn = $('#btn-play-pause');
    let nextBtn = $('#btn-next');
    let seekBarFill = $('.seek-bar .fill');

    let tracks = [
        'http://traffic.libsyn.com/minutephysics/Why_You_Should_Care_About_Nukes.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/Transporters_and_Quantum_Teleportation.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/The_Limb_of_the_Sun.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/_1.mp4?dest-id=95145',
        'http://traffic.libsyn.com/minutephysics/Concrete_Does_Not_Dry_Out.mp4?dest-id=95145'
    ];
    let audio = new Audio();
    let currentTrack = 0;
    let currentTime = 0;

    function playTrack() {
        audio.src = tracks[currentTrack];
        trackTitle.html('<a href=' + tracks[currentTrack] + '>' + tracks[currentTrack] + '</a>');
        audio.currentTime = currentTime;
        audio.play().then(function() {
            $('#btn-play-pause img').attr('src', 'static/pause.png');
        });
    }

    function playOrPauseTrack() {

        if(audio.paused) {
            console.log('play clicked');
            audio.currentTime = currentTime; // attempted workaround, still not working
            playTrack();
            console.log('play/current time=' + audio.currentTime);
        } else {
            console.log('pause clicked');
            audio.pause();
            currentTime = audio.currentTime;
            console.log('pause/current time=' + currentTime);
            $('#btn-play-pause img').attr('src', 'static/play.png');
        }
    }
});

【问题讨论】:

  • 我应该补充一点,我正在 Safari 13.0.5 上尝试这个。同样的行为也出现在 Chrome 80.0.3987.149 上。我的机器正在运行 Mac OS Catalina。

标签: javascript jquery html


【解决方案1】:

当您设置音频元素的 src 属性时,您将重置所有内容。

只需不要设置它,也不要重置currentTime。您只需拨打.play() 即可继续播放。

【讨论】:

  • 哇,这么简单的解决方案,我正要扯掉头发。谢谢!在约 10 分钟的冷却时间过后将接受作为答案。
  • @samisnotinsane 最简单的事情总是最令人沮丧的。 :-)
猜你喜欢
  • 2015-04-03
  • 1970-01-01
  • 2014-08-21
  • 2012-05-06
  • 2011-08-09
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多