为什么音频无法在移动浏览器上播放 [英] Why audio not playing on mobile browser

查看:85
本文介绍了为什么音频无法在移动浏览器上播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整天都在搜索.我知道自动播放无法在移动设备上运行,这是有道理的.但是我想知道为什么这不起作用.有没有解决的办法.下面的代码在台式机上完美运行,但在移动设备上无法正常运行.

I have been searching all day. I know that autoplay does not work on mobile and that makes sense. But i want to know why is this not working. Is there a work around for this. The below code works perfectly on desktop but not on mobile.

var audio = new Audio('sound.mp3');
audio.play();

推荐答案

一个非常老的问题,但是在解决我的问题的过程中我遇到了几次,那是音频在台式机上似乎工作得很好,但不是在某些移动浏览器上完全没有.

Very old question but I ran into it a few times on my journey to the solution to my problem which was that audio seemed to work perfectly fine on desktop but not at all on select mobile browsers.

我的问题是,在touchevent中我正在执行e.preventDefault(),这(某种程度上)使事件不可信",这意味着一切看起来都很好,但是没有音频可以播放.

My problem was that in a touchevent I was doing e.preventDefault() which (somehow?) made the event 'not trusted' meaning everything looked fine but no audio would play.

我通过不使用touch事件并依靠在CSS中设置touch-action: manipulation之后触发的click事件来修复了它.不是最好的解决方案,但是嘿.在控件上轻按一下该事件就变得不可信任,从而在默认情况下以阻止默认方式播放声音,从而使该事件在双击时不会放大.

I fixed it by just not using the touch event and relying on the click event which is fired after and setting touch-action: manipulation in the css. Not the best solution, but hey. Pretty silly the event becomes non-trusted on a tap on a control to play the sound with a prevent default so that it won't zoom in on a double tap.

希望这对遇到类似问题的人有所帮助.

Hopefully this helps someone with a similar problem.

(摘自Manuel Graf对问题的评论)

(from comment from Manuel Graf on this question)

这篇关于为什么音频无法在移动浏览器上播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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