更改源参数后 MP4 无法在移动设备上运行

MP4 not working on mobile devices after change source parameter

我有一个奇怪的问题。

在我客户的网站上,我使用 HTML5 视频元素展示了一些 mp4 文件。加载时在页面上可见的视频可以毫无问题地显示在移动设备上。

当我尝试更改视频元素的源时(在 AJAX 请求之后),视频元素显示黑屏。我更改的新视频源可能与页面加载时已显示的完全相同,但在更新 src 参数后它不会显示..

已经尝试检查 mp4 编码(即 H.264),服务器 response-headers 中的 content-type 是正确的(video/mp4)并且服务器似乎 return “206 部分内容”。此外,mp4 文件的 gzip 编码已关闭。

如果我在 Safari 中检查远程调试器(在 iPad 上检查 Safari),我收到错误 "An error occurred trying to load the resource"。您可以在下方找到回复 headers:

HTTP/1.1 206 Partial Content
Content-Type: video/mp4
ETag: "23f72-5a4561b99803e"
Last-Modified: Tue, 28 Apr 2020 09:03:40 GMT
Content-Range: bytes 0-147313/147314
Accept-Ranges: bytes
Date: Wed, 29 Apr 2020 05:13:12 GMT
Content-Length: 147314
Keep-Alive: timeout=5, max=84
Connection: Keep-Alive
Server: Apache

有谁知道可能导致此问题的原因是什么? 谢谢!

这方面的文档可能有点混乱 - 看起来无法动态更改源 (https://html.spec.whatwg.org/multipage/embedded-content.html):

Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.

但是,它可以更改,下面的代码片段应该可以跨浏览器可靠地工作 - video.load() 行是关键,因为它实际上确保插入了新源。您可以通过注释掉这一行并查看差异来进行试验:

var video = document.getElementById('video');
var source = document.createElement('source');

source.setAttribute('src', 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4');

video.appendChild(source);
video.play();

function changeSource() {  
    video.pause();

    source.setAttribute('src', 'http://clips.vorwaerts-gmbh.de/VfE_html5.mp4'); 

    video.load();  //This step is key
    video.play();
}
<h1>Video source change test</h1>
<p>
<button id="sourceButtom" onclick="changeSource()">Click me to change the video source.</button>
<p>
<video id="video" width="320" controls height="240"></video>

以上内容基于这里的优秀答案: