Wfs.js实现低延时H.264裸流播放
一、关键字
Vue框架、wfs.js、H.264、Websocket
二、步骤
此次用到的是项目中的wfs.js和 index.html这两个文件。
首先在你的项目中的视频页里根据情况加上下面这段代码,注意路径。
<script type="text/javascript" src="/dist/wfs.js" ></script>
<div class="wfsjs">
<video id="video1" width="640" height="480" controls></video>
<div class="ratio"></div>
</div>
<script type="text/javascript" src="/dist/wfs.js>
window.onload = function () {
if (Wfs.isSupported()) {
var video1 = document.getElementById("video1"),
wfs = new Wfs();
wfs.attachMedia(video1,'ch1');
}
};
</script>
在Vue中可以这样写:
<template>
<div id="Video">
<div id="videoBorder">
<video id="video1" width="640" height="480" autoplay></video>
</div>
</div>
</template>
<script>
import wfs from '../service/wfs.js'
import {split,initWebpack,websocketSend, websocket} from '../service/WebSocket'
window.onload = function() {
if (Wfs.isSupported()) {
var video1 = document.getElementById("video1"),
wfs = new Wfs();
wfs.attachMedia(video1, 'ch1');
}
};
...
然后在你添加到项目中的wfs.js文件中更改你的websocket连接路径,搜索onMediaAttached
找到创建websocket的函数,按以下方式修改:
key: 'onMediaAttached',
value: function onMediaAttached(data) {
if (data.websocketName != undefined) {
var url = "你的连接地址"
var client = new WebSocket(url)
//clientSocket = client
//(如果你要调用wfs.js中的websocket发送函数,你需要用到这行代码)
this.wfs.attachWebsocket(client, data.channelName);
} else {
console.log('websocketName ERROE!!!');
}
}
- 去掉缓存:注释
onSBUpdateEnd
方法里的this.mediaSource.endOfStream()
和that.media.play()
这两行,然后在video
标签里加上autoplay
,去掉controls
。 - 调整播放速度:将
this.H264_TIMEBASE = 3000
中的数值改为4500,有两个地方需要修改。
现在你就可以在浏览器上运行你的项目,看看是否有画面出现。在项目试验过程中可能出现以下问题:
1.花屏:可能是服务端出了问题,可以在服务端写文件进行测试。
2.可能会出现mediaError的打印日志,但并不影响画面播放。
如果你想在外部调用websocket发送你的项目所要求的请求视频数据,请接着看。
下面是接受H.264裸流并进行转化的函数:
key: 'receiveSocketMessage',
value: function receiveSocketMessage(event) {
this.buf = new Uint8Array(event.data);
var copy = new Uint8Array(this.buf);
if (this.mediaType === 'FMp4') {
this.wfs.trigger(_events2.default.WEBSOCKET_ATTACHED, { payload: copy });
}
if (this.mediaType === 'H264Raw') {
this.wfs.trigger(_events2.default.H264_DATA_PARSING, { data: copy });
}
}
在整个wfs.js文件函数的最外层定义变量:
var sendMsg;
var clientSocket;
在send函数中赋值:
key: 'onWebsocketMessageSending',
value: function onWebsocketMessageSending(i) {
clientSocket.send(i)
console.log('发送数据:' + i)
//this.client.send(i)
//this.client.send(JSON.stringify({ type: 2, carNum: 8888 }))
sendMsg = onWebsocketMessageSending
}
在函数最后export出去:
export {
sendMsg,
clientSocket,
}
在你想调用的页面import:
import {sendMsg,clientSocket} from '../service/wfs.js'