HTML5 音频标签在 Android 中不起作用 - Chrome 在 JS 中创建时?

HTML5 audio tag does not work in Android - Chrome when created in JS?

我正在使用 .mp3 文件,直接查看和使用 HTML5 音频标签嵌入时,.mp3 文件播放正常,但是在 JS 中创建 HTML5 音频标签时它不玩! (很奇怪)

我在任何其他 browser/device 中都没有这个问题,例如桌面 - Chrome 完美运行。

sound = document.createElement('audio');
sound.setAttribute('src', 'sound.mp3');
sound.play();

我已经测试了 sound.canPlayType('audio/mpeg'),这会产生 true(所以它是受支持的)。

也许 Android - Chrome 中存在错误? (是最新版本)

并非每个平台上的每个浏览器都可以播放 mp3 音频格式。一般来说,正如我建议的那样,您应该在音频元素中提供两个 <source> 元素,一个提供 mp3 格式,另一个提供 ogg vorbis 格式。

您可以在这里阅读更多内容:https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats

尝试将其附加到文档正文中。

document.body.appendChild(sound);

尽管移动设备可能不会自动播放音频或视频。如果您的目标是移动设备,自动播放被认为是不好的做法,因为它会消耗带宽。所以可能值得考虑添加控件。

sound.setAttribute('controls', 'true');

看起来这是预期的功能,它不仅涵盖 Chrome 浏览器。需要用户交互才能播放媒体元素。

Blink and WebKit have a setting for requiring a “user gesture” to play or pause an audio or video element, which is enabled in Opera for Android, Chrome for Android, the default Android browser, Safari for iOS and probably other browsers. This makes some sense, since mobile devices are used in public and in bed, where unsolicited sound from random Web sites could be a nuisance. Also, autoplaying video ads would waste bandwidth. Block Quote from 'blog.foolip.org'

来自其他用户的重复主题

Autoplay audio on mobile safari

How can I autoplay media in ios 4.2.1

Autoplay audio with ios 5 workaround?

当前状态

开发人员已请求删除 'mediaPlaybackRequiresUserGesture',该请求已被审查并被拒绝(目前)。 "We're going to gather some data about how users react to autoplaying videos in order to decide whether to keep this restriction."

经过进一步检查,我发现了这个...

"I misunderstood the outcome of the discussion (removing mediaPlaybackRequiresUserGesture) surrounding this topic. We need to keep this code in order to not break google.com while gathering data about this feature."

Google.com 依赖于被禁用的功能,否则它会破坏(他们没有说它破坏了什么)。

Original Bug Report

好吧,既然我们知道它不适用于 audio,您唯一的选择就是切换到网络音频 API。您需要将 mp3 加载到 ArrayBuffer 中(例如使用 XHR),然后将其传递给 decodeAudioData method, which gets you an Audio buffer that you can play back at will from an AudioBufferSourceNode.