目前,我正在尝试使用 HlsJS 在我的 Web 应用程序中播放 m3u8 视频,但是当我加载视频时,无论自动播放属性如何,它都会在我第一次加载时开始播放。
这是我的javascript代码:
const videoElement = document.getElementById(<unique-id>)
const hls = new Hls()
hls.loadSource(src)
hls.attachMedia(videoElement)
hls.on(Hls.Events.MEDIA_ATTACHED, function () {
console.log('media attached')
})
hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
})
hls.on(Hls.Events.MANIFEST_LOADED, function () {
})
注意这里我使用了这个 hls 文件:
https://cdnjs.cloudflare.com/ajax/libs/hls.js/1.4.3/hls.min.js
以下代码是html标签:
<video
id={uniqueKey}
muted={muted}
loop={loop}
height='100%'
width='100%'
playsInline
/>
我也试过将 eventListener 添加为并停止视频,但它也不起作用:
videoElement.addEventListener('canplay', () => {
videoElement.pause()
})
在这里,我期待 m3u8 视频在我加载视频时停止。
您是否尝试覆盖 hlsOptions autoStartLoad?
如果这是你的意思,请告诉我,我已经在视频中添加了海报并启用了控件,如果不需要就删除它。
<video id="myVideo" muted loop height="50%" width="50%" playsinline controls></video>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const videoElement = document.getElementById('myVideo');
const hls = new Hls();
hls.loadSource('https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8');
hls.attachMedia(videoElement);
hls.on(Hls.Events.MEDIA_ATTACHED, function () {
console.log('Media attached');
extractPosterFromVideo(videoElement);
});
hls.on(Hls.Events.MANIFEST_PARSED, function () {
videoElement.pause();
console.log('Manifest parsed');
});
hls.on(Hls.Events.MANIFEST_LOADED, function () {
videoElement.pause();
console.log('Manifest loaded');
});
// Code is for Poster/Thumbnail of the video at 3 seconds scene
function extractPosterFromVideo(video) {
// Seek to the desired time in seconds
const seekTime = 3;
video.currentTime = seekTime;
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
// Set the canvas size to match the video dimensions
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
video.addEventListener('seeked', function() {
context.drawImage(video, 0, 0, canvas.width, canvas.height);
const imageData = canvas.toDataURL();
video.setAttribute('poster', imageData);
});
}
});
</script>
干杯!