我有一个视频聊天应用程序,我想向其中添加UI控件。我在结束通话按钮上遇到问题。我可以结束通话,但无法弄清楚如何通过最后一行中的按钮删除视频框。如果我通过更改URL结束通话或关闭标签,它将删除视频框。
客户端脚本
const socket = io('/')
const videoGrid = document.getElementById('video-grid')
const myPeer = new Peer(undefined, {
host: '/',
port: '3001'
})
// Creating the <video> tag and muting the audio of your own feed
const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
addVideoStream(myVideo, stream)
// answering the call and sending your stream
myPeer.on('call', call => {
call.answer(stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
})
socket.on('user-connected', userId => {
connectToNewUser(userId, stream)
})
})
socket.on('user-disconnected', userId => {
if (peers[userId]) peers[userId].close()
})
myPeer.on('open', id => {
socket.emit('join-room', ROOM_ID, id)
})
// connect to new users and adding their video
function connectToNewUser(userId, stream) {
const call = myPeer.call(userId, stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
// removes video from grid once they disconnect
call.on('close', () => {
video.remove()
})
peers[userId] = call
}
// connect your video and append to grid
function addVideoStream(video, stream) {
video.srcObject = stream
video.addEventListener('loadedmetadata', () => {
video.play()
})
videoGrid.append(video)
}
// button to end call
let endCall = () => myVideo.srcObject.getTracks().forEach(track => track.stop())
服务器脚本
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.redirect(`/${uuidV4()}`)
})
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
server.listen(3000)
答案 0 :(得分:0)
对于其他可能遇到此问题的人,我的解决方法是制作一个html页面,单击该链接时,结束呼叫按钮会将用户定向到该页面。这样,URL就会发生变化,从而使视频流立即消失,从而解决了问题。