examples: fix websocket-client audio playback

This commit is contained in:
Aleix Conchillo Flaqué
2024-05-30 14:48:22 -07:00
parent 533c09741c
commit d2117c6f32

View File

@@ -16,6 +16,7 @@
<script> <script>
const SAMPLE_RATE = 16000; const SAMPLE_RATE = 16000;
const NUM_CHANNELS = 1; const NUM_CHANNELS = 1;
const PLAY_TIME_RESET_THRESHOLD_MS = 1.0;
// The protobuf type. We will load it later. // The protobuf type. We will load it later.
let Frame = null; let Frame = null;
@@ -39,6 +40,9 @@
// AudioContext play time. // AudioContext play time.
let playTime = 0; let playTime = 0;
// Last time we received a websocket message.
let lastMessageTime = 0;
// Whether we should be playing audio. // Whether we should be playing audio.
let isPlaying = false; let isPlaying = false;
@@ -82,9 +86,12 @@
return false; return false;
} }
if (playTime == 0) { // Reset play time if it's been a while we haven't played anything.
const diffTime = audioContext.currentTime - lastMessageTime;
if ((playTime == 0) || (diffTime > PLAY_TIME_RESET_THRESHOLD_MS)) {
playTime = audioContext.currentTime; playTime = audioContext.currentTime;
} }
lastMessageTime = audioContext.currentTime;
// We should be able to use parsedFrame.audio.audio.buffer but for // We should be able to use parsedFrame.audio.audio.buffer but for
// some reason that contains all the bytes from the protobuf message. // some reason that contains all the bytes from the protobuf message.