forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai.ts
More file actions
39 lines (32 loc) · 1.25 KB
/
Copy pathopenai.ts
File metadata and controls
39 lines (32 loc) · 1.25 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
import axios from "axios";
import { keys } from "../keys";
let audioContext: AudioContext;
export async function startAudio() {
audioContext = new AudioContext();
}
export async function textToSpeech(text: string) {
try {
const response = await axios.post("https://api.openai.com/v1/audio/speech", {
input: text, // Use 'input' instead of 'text'
voice: "nova",
model: "tts-1",
}, {
headers: {
'Authorization': `Bearer ${keys.openai}`, // Replace YOUR_API_KEY with your actual OpenAI API key
'Content-Type': 'application/json'
},
responseType: 'arraybuffer' // This will handle the binary data correctly
});
// Decode the audio data asynchronously
const audioBuffer = await audioContext.decodeAudioData(response.data);
// Create an audio source
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start(); // Play the audio immediately
return response.data;
} catch (error) {
console.error("Error in textToSpeech:", error);
return null; // or handle error differently
}
}