-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathspeak.ts
More file actions
66 lines (58 loc) · 1.74 KB
/
speak.ts
File metadata and controls
66 lines (58 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import sdk from 'microsoft-cognitiveservices-speech-sdk'
import fs from 'fs'
import sound from 'sound-play'
const speakQueue: string[] = []
export const speak = (text: string) => {
if (speakQueue.length > 0) {
speakQueue.push(text)
} else {
speakQueue.push(text)
processQueue()
}
}
export const processQueue = async () => {
if (speakQueue.length > 0) {
const text = speakQueue[0]
await actualSpeak(text)
speakQueue.shift()
await processQueue()
}
}
export const actualSpeak = async (text: string) => {
try {
await new Promise<void>((resolve) => {
const audioFile = './dist/_.wav'
const speechConfig = sdk.SpeechConfig.fromSubscription(
process.env.AZURE_SPEECH_KEY,
process.env.AZURE_SPEECH_REGION
)
const audioConfig = sdk.AudioConfig.fromAudioFileOutput(audioFile)
speechConfig.speechSynthesisVoiceName = process.env.AZURE_SPEECH_VOICE
let synthesizer = new sdk.SpeechSynthesizer(speechConfig, audioConfig)
synthesizer.speakTextAsync(
text,
async (result) => {
synthesizer.close()
synthesizer = null
if (result.reason === sdk.ResultReason.SynthesizingAudioCompleted) {
const absoultePath = fs.realpathSync(audioFile)
await sound.play(absoultePath, 1)
} else {
throw new Error(
'Speech synthesis canceled, ' +
result.errorDetails +
'\nDid you set the speech resource key and region values?'
)
}
resolve()
},
(err) => {
console.trace('err - ' + err)
synthesizer.close()
synthesizer = null
resolve()
}
)
})
} catch (e) {}
}