在Chrome for Android上获取音频持续时间 [英] Get audio duration on Chrome for Android

查看:220
本文介绍了在Chrome for Android上获取音频持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取文件的音频/视频持续时间,而不会将其附加到屏幕上。 使用相同的代码,当我尝试获取双方的视频时长时,它按预期工作。但是当使用音频文件时,它表示在Android上持续时间为0 ,但它适用于台式计算机。

I'm getting the audio/video duration of a file without appending it to the screen. "Using the same code", when I try to get the video duration on both sides it works as expected. But when using audio files it says that the duration is 0 on Android, but it works on a desktop computer.

// Only working on Desktop
var audio = new Audio(url);

// Hide audio player
// player.appendChild(audio);

audio.addEventListener('loadedmetadata', function() {
  alert(audio.duration);
});

以下代码正常运作:

// Working on Desktop and Android
var video = document.createElement('video');
video.src = url;

// Hide video
// player.appendChild(video);

video.addEventListener('loadedmetadata', function() {
  alert(video.duration);
});


推荐答案

编辑:使用 durationchange 事件更容易。首先输出0,但是一旦加载文件(这就是 loadedmetadata 失败,我猜),将输出更新的实际持续时间。

Using the durationchange event is much easier. First the 0 is being output, but as soon as the file is loaded (that's where loadedmetadata fails I guess) the updated and real duration will be output.

audio.addEventListener('durationchange', function(e) {
    console.log(e.target.duration); //FIRST 0, THEN REAL DURATION
});




老方式(上面更快)

看起来这个错误(如果这实际上是一个真正的错误)仍然存在。 Chrome(40)for Android仍然输出0作为音频文件的持续时间。研究网络并没有给我一个解决方案,但我发现这个bug也发生在iOS上。我想我应该在这里为你们发布我的修复。

Looks like this "bug" (if this is actually a real bug) is still around. Chrome (40) for Android still outputs 0 as the audio files duration. Researching the web didn't get me a solution but I found out the bug also occurs on iOS. I figured I should post my fix here for you guys.

audio.duration 输出0时,记录音频输出对象,你可以看到持续时间就在那里显示。所有这些都发生在 loadedmetadata 事件中。

While audio.duration outputs 0, logging audio outputs the object and you can see that the duration is displayed just right there. All this is happening in the loadedmetadata event.

audio.addEventListener('loadedmetadata', function(e) {
    console.log(e.target.duration); //0
});

如果你在 timeupdate 事件中记录audio.duration,那么真实正在输出持续时间。要只输出一次,你可以这样做:

If you log audio.duration in the timeupdate event though, the real duration is being output. To only output it once you could do something like:

var fix = true;
audio.addEventListener('timeupdate', function(e) {
    if(fix === true) {
        console.log(e.target.duration); //REAL DURATION
        fix = false;
    }
    console.log(e.target.currentTime); //UPDATED TIME POSITION
});

我不确定为什么会发生这一切。但是,让我们感到高兴的是,这并不严重。

I'm not sure why all this is happening. But let's be happy it's nothing serious.

这篇关于在Chrome for Android上获取音频持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆