如何实现微信中视频自动播放?
首先视频静音是可以实现自动播放的,但是微信中,MP4播放会受到限制
我们该如何让视频在微信中也能自动播放呢?
一. 首先需要利用 jsmpeg 将视频转化为ts格式
如何将mp4视频转换为.ts格式?? 参考:github.com/phoboslab/j…
- 在mac上安装Homebrew
- 在mac上安装ffmpeg,
- 安装完之后使用命令转换视频
ffmpeg -i in.mp4 -f mpegts -codec:v mpeg1video -codec:a mp2 -b 0 out.ts
二. 利用canvas进行渲染
代码示例
<img id="fallbackImage" class="fallback-image" src="封面图.png" alt="Fallback Image" >
<div id="videoContainer" class="video-container">
<canvas id="bgVideo" class="background-video"></canvas>
</div>
<script src="./style/js/jsmpeg.min.js"></script>
<script>
$(document).ready(function () {
resizeBgImage();
resizeVideo();
const query = decodeURIComponent(window.location.search.slice(1) || "");
const queryObj = formatQuery(query);
if (queryObj.ratingGuides === 'true') {
_app.openLayer({boxCell: '.year-layer', type: 'open'});
$('.year-layer .year-close').hide();
}
});
function resizeBgImage(){
const width = window.innerWidth;
const height = window.innerHeight;
const transformHeight = width * 1626 / 750;
$('#fallbackImage').css({
width: width,
height: transformHeight - height >= 20 ? transformHeight : height,
top: transformHeight - height >= 20 ? height - transformHeight - 20 : 0
});
}
function resizeVideo(){
const width = window.innerWidth;
const height = window.innerHeight;
const transformHeight = width * 1626 / 750;
$('#bgVideo').css({
width: width,
height: transformHeight - height >= 20 ? transformHeight : height,
top: transformHeight - height >= 20 ? height - transformHeight - 20 : 0
});
}
// 把query转换成对象
function formatQuery(str) {
const queryArr = str.split("&");
const queryObj = queryArr.reduce((obj, i) => {
const [key, value] = i.split("=");
obj[key] = value;
return obj;
}, {});
return queryObj;
}
$('.download-btn').click(function () {
_app.openLayer({boxCell: '.ptr-info', type: 'open'})
_app.setGtag('download_mobile_index')
$('#Ptr').load('../info.html')
})
window.addEventListener('resize', function() {
resizeBgImage();
resizeVideo();
});
</script>
<script>
// const videoUrl = 'https://xxx.com/video/index_750.ts'; // 替换为您的 TS 视频文件路径
// const videoUrl = ''; // 替换为您的 TS 视频文件路径
const fallbackImage = document.getElementById('fallbackImage');
const videoContainer = document.getElementById('videoContainer');
// 初始化并播放视频
function playVideo() {
/* const canvas = document.createElement('canvas');
canvas.className = 'background-video';
videoContainer.appendChild(canvas);*/
const canvas = document.getElementById('bgVideo');
const player = new JSMpeg.Player(videoUrl, {
// videoBufferSize: 512*1024, //视频缓冲区大小,可以调整
// audioBufferSize: 128*1024, //音频缓冲区大小,可以调整
bufferSize: 1024 * 1024, // 设置为 1MB 缓冲区
canvas: canvas,
autoplay: true,
loop: true,
audio: false,
onPlay: function(){
// 视频开始播放时隐藏备用图片
fallbackImage.style.zIndex = -1;
},
});
}
// 调用函数播放视频
playVideo();
</script>
<style>
.video-container{
position: relative;
width: 100%;
height: 176vw;
/* height: 100%; */
}
.background-video{
position: absolute;
top: 0;
left: 0;
}
</style>
jsmpeg.min.js 文件
github: github.com/phoboslab/j…