我的项目需求是连接客户提供的相机,得到相机的监控画面,呈现在前端页面中。
1.先创建请求
import axios from 'axios'
const whepClient = axios.create({
baseURL: 'http://192.xxx.xxx.xxx:xxx',
headers: {
'Content-type': 'application/sdp',
},
})
export default whepClient
2.创建video元素
<div class="video2">
<video ref="videoPlayer2" src="" style="width:100%;max-height:100%; object-fit: cover;"
autoplay muted controls="controls"></video>
</div>
3.编写实现方法
async playStream() {
this.pc = new RTCPeerConnection();
// 添加一个接收器的视频传输
this.pc.addTransceiver('video', { direction: 'recvonly' })
// 创建一个offer消息
const offer = await this.pc.createOffer()
// 设置本地的描述信息
await this.pc.setLocalDescription(offer)
// 将offer消息转换为SDP格式
this.offerSDP = offer.sdp
// 监听本地ice候选者
this.pc.onicecandidate = this.onLocalIceCandidate
// 监听本地ice收集状态改变
this.pc.onicegatheringstatechange = this.onLocalIceGatheringStatechange
// 监听远程接收器
this.pc.ontrack = this.onRcvdRemoteTrack
},
onLocalIceCandidate(event) {
if (event.candidate) {
if (this.offerSDP) {
this.offerSDP += ('a=' + event.candidate.candidate + '\r\n')
}
}
},
这里的方法要注意,如果你们要连接人家提供的设备,要知道设备的 ip 地址
async onLocalIceGatheringStatechange() {
if (this.pc) {
// 判断iceGatheringState是否为complete
if (this.pc.iceGatheringState === 'complete') {
try {
// 发送post请求,携带offerSDP和AbortSignal ${props.httpOfferApi}
const response = await whepClient.post('设备的ip地址(和后台对应)', this.offerSDP, {
// signal: AbortSignal.timeout(WHEP_REQUEST_TIMEOUT),
// 设置超时信号,当请求超过WHEP_REQUEST_TIMEOUT毫秒时,自动取消请求
})
if(response){
this.isflag = 1
}
if (response.status === 201) {
// 设置pc的远程描述
await this.pc.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: response.data,
}))
// // 资源名称为whep/location
// this.resourceURN = 'whep/' + response['headers']['location']
}
} catch (e) {
console.log(e);
}
}
}
},
onRcvdRemoteTrack(event) {
console.log(event, 'event')
// 获取远端视频的DOM元素
const domVideo = this.$refs.videoPlayer // document.getElementById('remoteVideo') as HTMLVideoElement
// 判断远端视频的DOM元素是否存在
if (domVideo) {
// 获取事件的streams属性
const [remoteStream] = event.streams
// 将远端视频的srcObject设置为remoteStream
domVideo.srcObject = remoteStream
}
}
4.最后调用 playStream 方法