wavServerTest/client/player.html

65 lines
1.6 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>WebSocket Audio Stream</title>
</head>
<body>
<h1>WebSocket Audio Stream</h1>
<audio id="audioPlayer" controls></audio>
<button onclick="startStream()">Start Stream</button>
<script>
const audioPlayer = document.getElementById('audioPlayer');
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const queue = [];
let source = null;
let nextTime = 0;
const processQueue = () => {
if (queue.length > 0) {
const data = queue.shift();
// queue.length=0;
audioContext.decodeAudioData(data.buffer, (buffer) => {
if (!source || nextTime < audioContext.currentTime) {
nextTime = audioContext.currentTime;
}
source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
// if(audioContext.)
source.start(nextTime);
nextTime += buffer.duration;
},err=>{
console.error('解码失败',err)
});
}
requestAnimationFrame(processQueue);
};
processQueue();
let startStream=()=>{
const ws = new WebSocket('ws://127.0.0.1:8000');
ws.binaryType = 'arraybuffer';
ws.onmessage = (event) => {
const data = new Uint8Array(event.data);
queue.push(data);
};
ws.onopen = () => {
console.log('WebSocket connection established');
};
ws.onclose = () => {
console.log('WebSocket connection closed');
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
</script>
</body>
</html>