node.js使用本地指定目录视频搭建多个实时流,同时使用socket.io监听.net服务和vue的请求指定实时流具体实现代码
时间: 2024-02-27 17:52:14 浏览: 101
以下是搭建多个实时流并使用socket.io监听.net服务和vue请求指定实时流的Node.js代码示例:
首先,需要安装以下依赖:
```
npm install express socket.io fluent-ffmpeg
```
然后,创建一个名为`server.js`的文件,写入以下代码:
```javascript
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const path = require('path');
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');
// 设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));
// 定义路由,返回index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
// 定义socket.io连接事件
io.on('connection', (socket) => {
console.log('A user connected');
// 监听客户端请求实时流事件
socket.on('request-stream', (streamName) => {
const streamPath = path.join(__dirname, 'streams', streamName + '.flv');
if (fs.existsSync(streamPath)) {
console.log(`Streaming ${streamName}...`);
socket.emit('streaming', streamName);
const ffmpegCommand = ffmpeg(fs.createReadStream(streamPath))
.inputFormat('flv')
.videoCodec('copy')
.audioCodec('copy')
.format('mpegts')
.on('error', (err) => {
console.log(`An error occurred while streaming ${streamName}: ${err.message}`);
})
.on('end', () => {
console.log(`${streamName} stream ended`);
});
ffmpegCommand.pipe(socket);
} else {
console.log(`Stream ${streamName} not found`);
socket.emit('stream-not-found', streamName);
}
});
// 监听断开连接事件
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
// 启动服务
server.listen(3000, () => {
console.log('Server started on port 3000');
});
```
接下来,在`public`目录下创建一个名为`index.html`的文件,写入以下代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Live Stream Player</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flv.js@^1.5.0/dist/flv.js"></script>
</head>
<body>
<h1>Live Stream Player</h1>
<div id="player"></div>
<script>
const socket = io();
const player = flvjs.createPlayer({
type: 'flv',
url: ''
});
player.attachMediaElement(document.getElementById('player'));
player.load();
// 监听服务端发送的实时流事件
socket.on('streaming', (streamName) => {
console.log(`Start streaming ${streamName}`);
player.pause();
player.attachMediaElement(document.getElementById('player'));
player.unload();
player.load();
player.play();
player.attachURL(`http://localhost:3000/live/${streamName}.ts`);
});
// 监听服务端发送的未找到实时流事件
socket.on('stream-not-found', (streamName) => {
console.log(`Stream ${streamName} not found`);
});
// 请求实时流
socket.emit('request-stream', 'stream1');
</script>
</body>
</html>
```
最后,在项目根目录下创建一个名为`streams`的目录,用于存储实时流文件。
运行`node server.js`启动服务,然后打开浏览器访问`http://localhost:3000`即可看到实时流播放器。通过修改`socket.emit('request-stream', 'stream1');`中的`stream1`参数,可以请求不同名称的实时流。
阅读全文