// Vue + WebRTC 示例代码
<template>
<div>
<button @click="startCall">Start Call</button>
<video ref="localVideo" autoplay muted></video>
<video ref="remoteVideo" autoplay></video>
</div>
</template>
<script>
export default {
data() {
return {
localStream: null,
peerConnection: null,
configuration: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' }
]
}
};
},
methods: {
async startCall() {
try {
// 获取本地媒体流
this.localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
this.$refs.localVideo.srcObject = this.localStream;
// 创建 RTCPeerConnection
this.peerConnection = new RTCPeerConnection(this.configuration);
// 添加本地流到 RTCPeerConnection
this.localStream.getTracks().forEach(track => {
this.peerConnection.addTrack(track, this.localStream);
});
// 监听远程流
this.peerConnection.ontrack = event => {
if (event.streams && event.streams[0]) {
this.$refs.remoteVideo.srcObject = event.streams[0];
}
};
// 处理 ICE 候选
this.peerConnection.onicecandidate = event => {
if (event.candidate) {
console.log('ICE candidate:', event.candidate);
}
};
// 创建 offer 并设置本地描述
const offer = await this.peerConnection.createOffer();
await this.peerConnection.setLocalDescription(offer);
// 模拟接收方设置远端描述(实际应用中应通过信令服务器传输)
setTimeout(async () => {
await this.peerConnection.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: '...' // 远端的 SDP 答案,实际应用中从信令服务器获取
}));
}, 1000);
} catch (error) {
console.error('Error starting call:', error);
}
}
}
};
</script>
<style scoped>
video {
width: 40%;
margin: 10px;
}
</style>
模板部分 (<template>):
<video>),一个用于显示本地视频流,另一个用于显示远程视频流。startCall 方法。脚本部分 (<script>):
data() 中定义了 localStream 和 peerConnection 变量,分别用于存储本地媒体流和 WebRTC 对等连接。configuration 定义了 STUN 服务器配置,用于 NAT 穿透。startCall 方法:navigator.mediaDevices.getUserMedia 获取本地媒体流,并将其绑定到本地视频元素。RTCPeerConnection 实例,并添加本地流到连接中。样式部分 (<style scoped>):
上一篇:vue2 emit
下一篇:vue使用axios解决跨域
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站