谷歌浏览器audio标签自动播放音乐问题解决

转自:https://blog.csdn.net/a545132569/article/details/82996445

前面一篇博客中有audio标签自动播放音乐的代码,可是后来再打开页面时音乐自动播放报错了;

看了网上的一些帖子才知道原来在4月份谷歌浏览器做了改革,不止谷歌,

其他浏览器好像也不支持自动播放了,现贴出解决方案:

1.在chrome 浏览器中输入:chrome://flags,搜索“Autoplay policy”,默认为“Default”,

修改为 “No user gesture is required” 就可以了;此方法仅限谷歌浏览器,而且比较笨拙,

但是问题可以解决;

2.在使用video标签的过程中,设置静音播放,问题也可以得到解决,但是对于有播放声音

要求的同学来说,问题还是得不到解决,代码如下:

<video controls muted autoplay >
        <source src="ifthisisthelove.mp3" type="video/mp4">
        <source src="ifthisisthelove.ogg" type="video/ogg">
    </video>

3.回到我使用的标签audio,使用这个标签自动播放时报错:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

这时我们自动播放是不成功的,解决办法如下:

function toggleSound() {
            var music = document.getElementById("vd");//获取ID  
                console.log(music);
                console.log(music.paused);
            if (music.paused) { //判读是否播放  
                music.paused=false;
                music.play(); //没有就播放
            }  
            
        }

setInterval("toggleSound()",1);

页面初始化时加载方法,自动播放;

猜你喜欢

转载自blog.csdn.net/qq_32849999/article/details/85051858