Last active
March 16, 2024 14:39
-
-
Save crashmax-dev/3fc85f1910236eff96da29119ca1b438 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// chat.ts | |
class Chat { | |
ws: WebSocket | |
onMessageCallback: (message: string) => void; | |
onMessage(callback: (message: string) => void): void { | |
this.onMessageCallback = callback; | |
} | |
async init(): Promise<void> { | |
this.ws = new WebSocket('ws://localhost:3000') | |
this.ws.addEventListener('message', (event) => { | |
const message = event.data | |
this.onMessageCallback(message) | |
}) | |
} | |
} | |
// main.ts | |
async function main() { | |
const tts = new Tts() | |
await tts.init() | |
const chat = new Chat(); | |
await chat.init(); | |
chat.onMessage((message) => { | |
tts.playMessage(message); | |
}); | |
} | |
// tts.ts | |
class Tts { | |
isPlaying = false; | |
messageQueue: string[] = []; | |
playMessage(message: string): void { | |
if (this.isPlaying || this.messageQueue.length > 0) { | |
this.messageQueue.push(message); | |
return | |
} | |
this.speech(message) | |
} | |
private async speech(message: string): Promise<void> { | |
this.isPlaying = true | |
await speechMessage(message) | |
this.isPlaying = false | |
this.nextMessage() | |
} | |
private nextMessage() { | |
const message = this.messageQueue.shift(); | |
if (message) { | |
this.speech(message) | |
} | |
} | |
async init() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment