webrtc/public/index.html

265 lines
11 KiB
HTML
Raw Normal View History

2023-09-27 14:26:12 +08:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webRTC</title>
</head>
<body>
<div>
<h1>webRTC</h1>
2023-09-28 23:49:26 +08:00
<p>选择音乐使频道内所有设备同步播放</p>
2023-09-27 14:26:12 +08:00
</div>
<script type="module">
2023-09-28 01:14:49 +08:00
import IndexedDB from './database.js'
2023-09-28 15:20:02 +08:00
import MusicList from './music.js'
2023-09-28 23:49:26 +08:00
import ClientList from './client.js'
2023-09-29 17:31:37 +08:00
2023-09-28 23:49:26 +08:00
// 初始化音乐列表
2023-09-28 15:20:02 +08:00
const musicList = new MusicList()
2023-09-29 01:12:20 +08:00
musicList.on('play', item => {
console.log('播放音乐', item)
})
2023-09-28 23:49:26 +08:00
// 初始化客户端列表
2023-09-29 17:31:37 +08:00
const clientList = new ClientList({
channels: {
'musicList': {
onopen: async (event, channel) => {
const list = await musicList.list
console.log('musicList:', list)
channel.send(JSON.stringify(list))
},
onmessage: async (event, channel) => {
console.log('收到 musicList:', event)
JSON.parse(event.data).forEach(item => {
musicList.push(item)
})
},
},
}
})
// 在什么时机发送musicList?
// 通道准备好时即可发送
2023-09-29 18:14:18 +08:00
// 获取对方的音乐列表
// like对方的条目时亮起(双方高亮)(本地缓存)(可由对比缓存实现)
// ban对方的条目时灰掉(也禁止对方播放)(并保持ban表)(由插件实现)
2023-09-29 17:31:37 +08:00
clientList.on('channel')
// 只需要在注册时拉取列表, 播放时才需要拉取音乐数据
2023-09-28 23:49:26 +08:00
2023-09-29 01:12:20 +08:00
// 先拉取所有对方的音乐列表, 对比去重, 拉取音乐数据
// 主动发送自己的音乐列表, 对比去重, 发送音乐数据
2023-09-29 17:31:37 +08:00
//clientList.on('list', async client => {
// console.log('push:', client)
// const musicList = await clientList.send('music-list', '23333')
// console.log('musicList:', musicList)
//})
2023-09-28 15:20:02 +08:00
2023-09-27 14:26:12 +08:00
// webRTC 传递音乐(分别传输文件和操作事件能更流畅)
const music = async function () {
2023-09-28 01:14:49 +08:00
const clients = [] // 客户端列表
2023-09-28 15:20:02 +08:00
// 对端设备
2023-09-27 15:01:03 +08:00
const ul = document.createElement('ul')
document.body.appendChild(ul)
2023-09-27 14:26:12 +08:00
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
const host = window.location.host
const ws = new WebSocket(`${protocol}://${host}/webrtc/music`)
const pc = new RTCPeerConnection()
2023-09-28 01:14:49 +08:00
2023-09-28 17:59:23 +08:00
var audioSource = null
// 监听音乐列表播放事件
musicList.on('play', async item => {
audioSource?.stop() // 先停止可能在播放的音乐
console.log('播放音乐', item.arrayBuffer)
// 复制一份 item.arrayBuffer
const arrayBuffer = item.arrayBuffer.slice(0)
// 传输音乐文件向远程端
const audioContext = new AudioContext()
audioContext.decodeAudioData(arrayBuffer, async audioBuffer => {
// 将音乐流添加到 RTCPeerConnection
const mediaStreamDestination = audioContext.createMediaStreamDestination()
mediaStreamDestination.stream.getAudioTracks().forEach(function (track) {
pc.addTrack(track, mediaStreamDestination.stream)
})
// 播放音乐(远程)
audioSource = audioContext.createBufferSource()
audioSource.buffer = audioBuffer
audioSource.connect(mediaStreamDestination)
audioSource.start()
// 创建SDP offer并将其设置为本地描述, 发送给指定的远程端
const id = clients[0].id
await pc.setLocalDescription(await pc.createOffer()) // 设置本地描述为 offer
ws.send(JSON.stringify({ id, offer: pc.localDescription })) // 发送给远程终端 offer
})
})
// 监听音乐列表停止事件
musicList.on('stop', async () => {
audioSource?.stop()
audioSource = null
})
2023-09-27 14:26:12 +08:00
// 监听 ICE 候选事件
pc.onicecandidate = event => {
if (event.candidate) {
const id = clients[0].id
ws.send(JSON.stringify({ id, candidate: event.candidate })) // 发送 ICE 候选到远程终端
}
}
// 监听远程流事件
pc.ontrack = function (event) {
console.log('pc ontrack:', event)
const audio = document.createElement('audio')
audio.srcObject = event.streams[0]
audio.play()
}
ws.onmessage = async (event) => {
const data = JSON.parse(event.data)
if (data.type === 'push') {
console.log('收到 type:push 将设备增加', data.id)
clients.push({ id: data.id, channel: data.channel })
2023-09-27 15:01:03 +08:00
const li = document.createElement('li')
li.innerText = `id:${data.id} channel:${data.channel}`
li.id = data.id
2023-09-27 21:36:55 +08:00
li.onclick = async () => {
console.log('点击设备', data.id)
// 清理所有选中状态
clients.forEach(client => {
const li = document.getElementById(client.id)
if (data.id === client.id) {
li.style.backgroundColor = 'red'
console.log('设置选中状态', data.id)
return
}
li.style.backgroundColor = 'transparent'
console.log('清理选中状态', client.id)
})
}
2023-09-27 15:01:03 +08:00
ul.appendChild(li)
2023-09-27 14:26:12 +08:00
return
}
if (data.type === 'pull') {
console.log('收到 type:pull 将设备删除', data.id)
const index = clients.findIndex(client => client.id === data.id)
if (index !== -1) {
clients.splice(index, 1)
2023-09-27 15:01:03 +08:00
const li = document.getElementById(data.id)
li.remove()
2023-09-27 14:26:12 +08:00
}
return
}
if (data.type === 'error') {
console.log('收到 type:error 没什么可操作的', data.id)
return
}
if (data.offer) {
const id = clients[0].id
console.log('收到 offer 并将其设置为远程描述', data.offer)
await pc.setRemoteDescription(new RTCSessionDescription(data.offer)) // 设置远程描述为 offer
await pc.setLocalDescription(await pc.createAnswer()) // 设置本地描述为 answer
2023-09-28 23:49:26 +08:00
ws.send(JSON.stringify({ id, answer: pc.localDescription })) // 发送给远程终端 answer
2023-09-27 14:26:12 +08:00
return
}
if (data.answer) {
console.log('收到 answer 并将其设置为远程描述', data.answer)
await pc.setRemoteDescription(new RTCSessionDescription(data.answer))
return
}
if (data.candidate) {
console.log('收到 candidate 并将其添加到远程端', data.candidate)
await pc.addIceCandidate(new RTCIceCandidate(data.candidate))
return
}
}
}
2023-09-28 23:49:26 +08:00
//music()
2023-09-27 14:26:12 +08:00
</script>
<!--script type="module">
// 创建 RTCPeerConnection
const pc = new RTCPeerConnection()
// webSocket 连接服务器
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
const host = window.location.host
const ws = new WebSocket(`${protocol}://${host}/webrtc/default`)
ws.onopen = function () {
console.log('video ws open')
}
ws.onmessage = function (event) {
const data = JSON.parse(event.data)
console.log('ws message:', data)
if (data.offer) {
console.log('收到 offer 并将其设置为远程描述')
pc.setRemoteDescription(new RTCSessionDescription(data.offer))
// 创建SDP answer并将其设置为本地描述, 发送给远程端
pc.createAnswer().then(function (answer) {
pc.setLocalDescription(answer);
ws.send(JSON.stringify({ answer }))
})
return
}
if (data.answer) {
console.log('收到 answer 并将其设置为远程描述')
pc.setRemoteDescription(new RTCSessionDescription(data.answer))
return
}
if (data.candidate) {
console.log('收到 candidate 并将其添加到远程端')
pc.addIceCandidate(new RTCIceCandidate(data.candidate))
}
}
ws.onclose = function () {
console.log('ws close')
}
setTimeout(() => {
// 获取本地视频流
navigator.mediaDevices.getUserMedia({ audio: false, video: true }).then(stream => {
// 创建本地视频元素
const localVideo = document.createElement('video');
localVideo.srcObject = stream;
localVideo.autoplay = true;
localVideo.muted = true;
document.body.appendChild(localVideo);
// 添加本地视频流到 RTCPeerConnection
stream.getTracks().forEach(function (track) {
pc.addTrack(track, stream);
});
// 监听 ICE candidate 事件
pc.onicecandidate = function (event) {
if (event.candidate) {
// 发送 ICE candidate 到远程端
ws.send(JSON.stringify({ candidate: event.candidate }))
}
};
// 监听远程视频流事件
pc.ontrack = function (event) {
// 创建远程视频元素
var remoteVideo = document.createElement('video');
remoteVideo.srcObject = event.streams[0];
remoteVideo.autoplay = true;
document.body.appendChild(remoteVideo);
}
// 创建SDP offer并将其设置为本地描述, 发送给远程端
pc.createOffer().then(function (offer) {
pc.setLocalDescription(offer);
ws.send(JSON.stringify({ offer }))
})
}).catch(error => {
console.log(error)
})
}, 1000)
</script-->
</body>
</html>