javascript 设置 <audio> 标签的 currentTime 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8621511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:00:52  来源:igfitidea点击:

Setting the currentTime of an <audio> tag not working?

javascripthtmlhtml5-audio

提问by fishbaitfood

I have this audio tag playing in the background, and I'm able to store the progress in seconds to a cookie. But in no way I'm able to start the audio from that cookie. (for continuing on other pages)

我在后台播放了这个音频标签,我能够将进度存储到 cookie 中。但我无论如何都无法从那个 cookie 开始播放音频。(在其他页面上继续)

$("p#sound audio").currentTime = $.cookie("audioTime");

<audio autoplay="autoplay" loop="loop" ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime); $.cookie('audioTime', Math.floor(this.currentTime));">
    <source src="audio/song.ogg" type="audio/ogg" />
    <source src="audio/song.mp3" type="audio/mp3" />
    Your browser does not support the audio tag.
</audio>
<span id="tracktime">0</span>

Does this have to do with the song being loaded again from start?

这与从头开始再次加载歌曲有关吗?

Thanks!

谢谢!

EDIT:

编辑:

$("p#sound audio").get[0].currentTime

With .get[0], it doesn't work either.

使用 .get[0],它也不起作用。

Can someone please clear things up for me? Greatly appreciated!

有人可以帮我清理一下吗?非常感激!

回答by Brian Hadaway

You need to wait until audiosource loads before you set the current time.

audio在设置当前时间之前,您需要等到源加载。

$(function(){
    $('audio').bind('canplay', function(){
        $(this)[0].currentTime = $.cookie('audioTime');
    });
});

回答by Codebeat

At first there is an error in your code because currentTime is not a part of jQuery (but you already know this)

起初你的代码有一个错误,因为 currentTime 不是 jQuery 的一部分(但你已经知道了)

$("p#sound audio").currentTime // is incorrect (refers to a property of jQuery)
$("p#sound audio")[0].currentTime // is correct (refers to a property of DOM element)

I discover that the audio tag has some strange things and can be operate differently from browser to browser, for example in Chrome.

我发现音频标签有一些奇怪的东西,并且可以在不同浏览器之间进行不同的操作,例如在 Chrome 中。

At first you have to wait for the 'durationchange' event to be sure the length is known by the object.

首先,您必须等待 ' durationchange' 事件以确保对象知道长度。

After this you have to start the stream with 'play()' (if not already started) and pause it (sometimes after a short delay) with the 'pause()' function. Then you can change the 'currentTime' property with the value. After this you have to start the stream again by using the 'play()' function.

在此之后,您必须使用“ play()”(如果尚未启动)启动流并使用“ ”功能暂停它(有时在短暂延迟后)pause()。然后您可以使用该值更改“currentTime”属性。在此之后,您必须使用'play()' 函数再次启动流。

Also it is sometimes needed to load the stream by yourself by using the 'load()' function.

此外,有时需要使用 ' load()' 函数自行加载流。

Something like this:

像这样的东西:

$(document).ready( function()
{
var a = $('audio:first'),
    o = a[0];

a.on( 'durationchange', function(e)
{
  var o = e.target;
  if( o )
  {
   o.pause();
   o.currentTime = parseInt( $.cookie("audioTime"));
   o.play();
  } 
});

if( o )
{
  o.load();
  o.play();
}
});

You have to play with it to be sure what is the best in your situation, for example the resume (play again) method to delay it for a second or so.

您必须使用它来确定在您的情况下什么是最好的,例如恢复(再次播放)方法将其延迟一秒钟左右。

When using this method you don't have to use the autoplay feature because most of the time it doesn't work.

使用此方法时,您不必使用自动播放功能,因为大多数情况下它不起作用。

Hope it helps, greetz, Erwinus

希望它有帮助,greetz,Erwinus

回答by Brian Beckett

You can set the start time by adding t=<time>to the URL, as documented here: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video#Specifying_playback_range

您可以通过添加t=<time>到 URL来设置开始时间,如下所述:https: //developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video#Specifying_playback_range

E.g. <audio src="http://example.com/audio.mp3#t=50></audio>

例如 <audio src="http://example.com/audio.mp3#t=50></audio>

回答by Gilson

what I found in my case is that there is an issue with context somewhere. I initialize audio under the window context but when I try to change currentTime from XMLHttpRequest response it does NOT work. I don't know the answer yet but I'm providing a clue maybe an expert in Javascript will know how to make it work.

在我的案例中,我发现某处的上下文存在问题。我在窗口上下文下初始化音频,但是当我尝试从 XMLHttpRequest 响应更改 currentTime 时,它​​不起作用。我还不知道答案,但我提供了一个线索,也许 Javascript 专家会知道如何使它工作。

/* initialize this.audio player */
Audio = function() {
    var that = this;
    // keep track of playback status
    var AudioStatus = {
            isPlaying : false
    };

    // define references to this.audio, pulldown menu, play-button, slider and time display
    that.audio = document.querySelector("AUDIO");

    /* load track by menu-index */
    var loadTrack = function() {

        if(that.audio == null){
            log("audio null"); return;
        }
        that.audio.src = '../sounds/400.mp3';
        that.audio.load();
    };

    /* callback to play or pause */
    that._play = function() {
        if(that.audio == null){
            log("audio null"); return;
        }  
        that.audio.play();
        AudioStatus.isPlaying = true;
    };

    that._pause = function() {

        if(that.audio == null){
            log("audio null"); return;
        }
        that.audio.pause();
        AudioStatus.isPlaying = false;
    };

    that.playPause = function() {
        if (that.audio.paused) {
            self._play();
        }
        else {
            self._pause();
        }
    };

    /* callback to set or update playback position */
    that.updateProgress = function(value) {
        if(that.audio == null){
            log("audio null"); return;
        }
        that.audio.currentTime = value;    // <<<--- it does NOT work if I call from XMLHttpRequest response but it DOES if it is called from a timer expired call back
    };

    that.isAudioPlaying = function(){
        return AudioStatus.isPlaying;
    };
};

回答by Hi?u Nguy?n Ng?c

This works for me.

这对我有用。

if (!isNaN(audio.duration)) {
    audio.currentTime = 0;
}

Hope it helps!

希望能帮助到你!

回答by Bart S

This solved it for me:

这为我解决了:


  $("p#sound audio").on('loadedmetadata', () => {
    $("p#sound audio").get(0).load();
  });

So I could later set the currentTimewithout worrying about whether the audio was loaded or not.

所以我以后可以设置而currentTime不用担心音频是否加载。