<template>
<div>
<h3>视频聊天</h3>
<video ref="localVideo" style="width: 400px;height: 300px;" @click="toggleFullscreen"></video>
<div style="text-align: left">
自己ID<input type="text" v-model="myPeerid" />
<br>
对方ID<input type="text" v-model="youPeerid" />
<br>
<button @click="startCaller">视频通话</button>
<button @click="startCall">确认</button>
<button @click="endCall">挂断</button>
</div>
<video ref="remoteVideo" style="width: 400px;height: 300px;" @click="toggleFullscreen"></video>
</div>
</template>
<script>
import { Peer } from 'peerjs'
export default {
data () {
return {
myPeerid: '',
youPeerid: '',
localStream: null,
remoteStream: null,
peer: null,
call: null
}
},
mounted () {
},
methods: {
startCaller () {
this.getUserMedia({ video: true, audio: true }, (stream) => {
this.localStream = stream
this.$refs.localVideo.srcObject = stream
this.$refs.localVideo.autoplay = true
this.$refs.localVideo.play()
}, (err) => {
console.log('获取本地流失败', err)
})
this.peer = new Peer()
this.peer.on('open', (id) => {
this.myPeerid = id
console.log(id, 'id')
})
this.peer.on('call', (call) => {
this.call = call
call.answer(this.localStream)
call.on('stream', (remoteStream) => {
console.log(remoteStream, '>>>>')
this.remoteStream = remoteStream
this.$refs.remoteVideo.srcObject = remoteStream
this.$refs.remoteVideo.autoplay = true
})
})
},
toggleFullscreen () {
const video = this.$refs.localVideo
if (video.requestFullscreen) {
video.requestFullscreen()
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen()
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen()
} else if (video.msRequestFullscreen) {
video.msRequestFullscreen()
}
},
getUserMedia (constraints, success, error) {
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error)
} else if (navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia(constraints).then(success).catch(error)
} else if (navigator.mozGetUserMedia) {
navigator.mozGetUserMedia(constraints).then(success).catch(error)
} else if (navigator.getUserMedia) {
navigator.getUserMedia(constraints).then(success).catch(error)
}
},
startCall () {
const remoteId = this.youPeerid
if (remoteId === '') {
alert('请输入对方ID')
return
}
this.call = this.peer.call(remoteId, this.localStream)
this.call.on('stream', (remoteStream) => {
console.log(remoteStream)
this.remoteStream = remoteStream
this.$refs.remoteVideo.srcObject = remoteStream
this.$refs.remoteVideo.autoplay = true
})
this.call.on('close', () => {
console.log('用户通话关闭')
})
this.call.on('error', (err) => {
console.log(err)
})
},
endCall () {
if (this.call) {
this.call.close()
this.call = null
}
this.remoteStream = null
this.$refs.remoteVideo.srcObject = null
this.myPeerid = null
this.localVideo = null
this.$refs.localVideo.srcObject = null
this.arr = true
}
}
}
</script>
12-28
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交