javascript - html5 audio 延时获取播放路径播放失败

查看:177
本文介绍了javascript - html5 audio 延时获取播放路径播放失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

为什么audio对象在延时1000毫秒之后就不能执行播放呢?
歌曲的路径需要从数据库中获取,所以需要用ajax来交互,但是发现假如时间过长即使获取到路径也不能执行播放。
为方便测试使用setTimeout来模拟

<!doctype html>
<html>
<head>
    <title>自动播放音乐测试</title>
    <meta charset="utf-8">
</head>
<body>
试试看能不能听到声音。
</body>
</html>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
    (function () {
        var a = new Audio();
        a.src = 'http://fztj.qz178.com/html/qz-yyxs/tjyy/42j-hj.mp3';

        $(document).click(function(){
            setTimeout(function(){
                a.play();
            }, 1000);
        })

    })();
</script>

以上代码在1000毫秒后可以正常播放,但如果超过1000毫秒就不能正常播放了,如下:

<!doctype html>
<html>
<head>
    <title>自动播放音乐测试</title>
    <meta charset="utf-8">
</head>
<body>
试试看能不能听到声音。
</body>
</html>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
    (function () {
        var a = new Audio();
        a.src = 'http://fztj.qz178.com/html/qz-yyxs/tjyy/42j-hj.mp3';

        $(document).click(function(){
            setTimeout(function(){
                a.play();
            }, 1001);
        })

    })();
</script>

求各位解惑!

解决方案

首先要了解, 在移动端播放音频视频必须是经过用户的操作才能执行的, 然后下面正式解决问题

引用外国友人(andreybavt)的原话:

I had to experiment with Chrome playing sounds. It turned out that even after a user gesture (such as click) it waits for 1000ms and if no sound was played it throws the exception above. In my case the problem was coming from asynchronous track URL loading.

But it also turned out that after the first track is played chrome doesn't care anymore for this 1000ms delay and you can call play programmatically with any timeout you want.

So the solution was to play a micro almost zero-second long muted sound from static resources after the very first time a user clicks on a track and after that load a desired track URL.

Hope it helps or someone finds other solutions.

大概意思就是如果异步操作1000毫秒内没有收到任何信息, 就会抛出异常(如下), 浏览器就不会把这个操作认为是来自用户的操作, 所以导致无法播放, 但有趣的是只要你的音频播放完一次后刚刚所说的1000毫秒规则就不会重复生效, 所以现在我的解决办法是在用户第一次点击播放的时候先播放一次没有声音且接近0秒的音频(当然你也可以播个几十秒=.=), 然后就可以愉快的异步了.

Uncaught (in promise) DOMException: play() can only be initiated by a user gesture.

详细文章可以参考: 原文传送门

这篇关于javascript - html5 audio 延时获取播放路径播放失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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