一、播放rtsp协议流
如果 webrtc 流以 rtsp 协议返回,流地址如:rtsp://127.0.0.1:5115/session.mpg
,uniapp的 <video>
编译到android上直接就能播放,但通常会有2-3秒的延迟。
二、播放webrtc协议流
如果 webrtc 流以 webrtc 协议返回,流地址如:webrtc://127.0.0.1:1988/live/livestream
,我们需要通过sdp协商、连接推流服务端、搭建音视频流通道来播放音视频流,通常有500毫秒左右的延迟。
封装 WebrtcVideo 组件
<template>
<video id="rtc_media_player" width="100%" height="100%" autoplay playsinline></video>
</template>
<!-- 因为我们使用到 js 库,所以需要使用 uniapp 的 renderjs -->
<script module="webrtcVideo" lang="renderjs">
import $ from "./jquery-1.10.2.min.js";
import {
prepareUrl} from "./utils.js";
export default {
data() {
return {
//RTCPeerConnection 对象
peerConnection: null,
//需要播放的webrtc流地址
playUrl: 'webrtc://127.0.0.1:1988/live/livestream'
}
},
methods: {
createPeerConnection() {
const that = this
//创建 WebRTC 通信通道
that.peerConnection = new RTCPeerConnection(null);
//添加一个单向的音视频流收发器
that.peerConnection.addTransceiver("audio", {
direction: "recvonly" });
that.peerConnection.addTransceiver("video", {
direction: "recvonly" });
//收到服务器码流,将音视频流写入播放器
that.peerConnection.ontrack = (event) => {
const remoteVideo = document.getElementById("rtc_media_player");
if (remoteVideo.srcObject !== event.streams[0]) {
remoteVideo.srcObject = event.streams[0];
}
};
},
async makeCall() {
const that = this
const url = this.playUrl
this.createPeerConnection()
//拼接服务端请求地址,如:http://192.168.0.1:1988/rtc/v1/play/
const conf = prepareUrl(url);
//生成 offer sdp
const offer = await this.peerConnection.createOffer();
await this.peerConnection.setLocalDescription(offer);
var session = await new Promise(function (resolve, reject) {
$.ajax({
type: "POST",
url: conf.apiUrl,
data: offer.sdp,
contentType: "text/plain",
dataType: "json",
crossDomain: true,
})
.done(function (data) {
//服务端返回 answer sdp
if (data.code) {
reject(data);
return;
}
resolve(data);
})
.fail(function (reason) {
reject(reason);
});
});
//设置远端的描述信息,协商sdp,通过后搭建通道成功
await this.peerConnection.setRemoteDescription(
new RTCSessionDescription({
type: "answer", sdp: session.sdp })
);
session.simulator = conf.schema + '//' + conf.urlObject.server + ':' + conf.port + '/rtc/v1/nack/'
return session;
}
},
mounted() {
try {
this