微信小程序 播放自己服务器上的视频分段视频,请写出例子和实现思路
时间: 2024-04-01 16:32:36 浏览: 18
实现思路:
1. 在服务器上将完整视频文件分成多个小视频文件,并将每个小视频文件的 URL 存储到数据库中。
2. 在微信小程序中,使用 wx.request() 方法向服务器请求视频分段的 URL。
3. 使用 wx.createVideoContext() 方法创建视频上下文对象,并使用它的 src 属性将视频分段的 URL 赋值给它。
4. 在用户点击播放按钮时,调用视频上下文对象的 play() 方法播放视频。
示例代码:
1. 服务器端代码(Node.js):
```javascript
const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
app.use(bodyParser.json());
// 连接 MongoDB 数据库
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
if (err) {
console.log('MongoDB 连接失败');
return;
}
console.log('MongoDB 连接成功');
const db = client.db('test');
// 将完整视频文件分成多个小视频文件
app.post('/video/split', (req, res) => {
const filePath = req.body.filePath;
const chunkSize = req.body.chunkSize;
const fileName = path.basename(filePath, path.extname(filePath));
const dirName = path.dirname(filePath);
const fileExt = path.extname(filePath);
const fileStat = fs.statSync(filePath);
const fileSize = fileStat.size;
const numChunks = Math.ceil(fileSize / chunkSize);
const chunks = [];
for (let i = 0; i < numChunks; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, fileSize);
const chunkPath = path.join(dirName, `${fileName}.${i}${fileExt}`);
const chunkStream = fs.createWriteStream(chunkPath);
fs.createReadStream(filePath, { start, end })
.on('error', (err) => {
console.log(err);
})
.pipe(chunkStream)
.on('error', (err) => {
console.log(err);
});
chunks.push({
url: `http://localhost:3000/video/chunk/${fileName}/${i}${fileExt}`,
size: end - start
});
}
// 将视频分段的 URL 存储到数据库中
db.collection('videos').insertOne({ name: fileName, chunks }, (err, result) => {
if (err) {
console.log(err);
res.status(500).send('Internal server error');
} else {
res.status(200).send('OK');
}
});
});
// 提供视频分段的 URL
app.get('/video/chunk/:name/:index', (req, res) => {
const name = req.params.name;
const index = req.params.index;
const chunkPath = path.join(__dirname, 'videos', `${name}.${index}`);
if (fs.existsSync(chunkPath)) {
res.status(200).sendFile(chunkPath);
} else {
res.status(404).send('Not found');
}
});
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
});
```
2. 微信小程序端代码:
```javascript
Page({
data: {
videoChunks: [], // 视频分段的 URL
currentChunkIndex: 0 // 当前播放的视频分段索引
},
onLoad() {
wx.request({
url: 'http://localhost:3000/video/split',
method: 'POST',
data: {
filePath: '/path/to/video.mp4',
chunkSize: 1024 * 1024 // 1MB
},
success: (res) => {
if (res.statusCode === 200) {
this.setData({
videoChunks: res.data.chunks
});
} else {
wx.showToast({
title: '视频分段失败',
icon: 'none'
});
}
},
fail: () => {
wx.showToast({
title: '服务器请求失败',
icon: 'none'
});
}
});
},
onPlay() {
const videoContext = wx.createVideoContext('video');
const currentChunk = this.data.videoChunks[this.data.currentChunkIndex];
videoContext.src = currentChunk.url;
videoContext.play();
},
onEnded() {
const currentChunkIndex = this.data.currentChunkIndex + 1;
if (currentChunkIndex < this.data.videoChunks.length) {
this.setData({
currentChunkIndex
}, () => {
this.onPlay();
});
}
}
});
```
注意事项:
1. 微信小程序只支持 HTTPS 协议的视频 URL,如果服务器没有配置 HTTPS,可以使用 ngrok 等工具将本地服务器的 HTTP 服务转换成 HTTPS 服务。
2. 微信小程序只支持 H.264 编码格式的视频。