Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e950ad9

Browse files
authoredDec 23, 2023
docs: improve audio example to show how to stream to a file (#598)
1 parent b595cd9 commit e950ad9

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed
 

‎examples/audio.ts

+41-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
#!/usr/bin/env -S npm run tsn -T
2+
import 'openai/shims/node';
23

34
import OpenAI, { toFile } from 'openai';
4-
import fs from 'fs/promises';
5+
import fs from 'fs';
56
import path from 'path';
67

78
// gets API Key from environment variable OPENAI_API_KEY
@@ -10,14 +11,34 @@ const openai = new OpenAI();
1011
const speechFile = path.resolve(__dirname, './speech.mp3');
1112

1213
async function main() {
14+
await streamingDemoNode();
15+
await blockingDemo();
16+
}
17+
main();
18+
19+
async function streamingDemoNode() {
20+
const response = await openai.audio.speech.create({
21+
model: 'tts-1',
22+
voice: 'alloy',
23+
input: 'the quick brown chicken jumped over the lazy dogs',
24+
});
25+
26+
const stream = response.body;
27+
28+
console.log(`Streaming response to ${speechFile}`);
29+
await streamToFile(stream, speechFile);
30+
console.log('Finished streaming');
31+
}
32+
33+
async function blockingDemo() {
1334
const mp3 = await openai.audio.speech.create({
1435
model: 'tts-1',
1536
voice: 'alloy',
1637
input: 'the quick brown fox jumped over the lazy dogs',
1738
});
1839

1940
const buffer = Buffer.from(await mp3.arrayBuffer());
20-
await fs.writeFile(speechFile, buffer);
41+
await fs.promises.writeFile(speechFile, buffer);
2142

2243
const transcription = await openai.audio.transcriptions.create({
2344
file: await toFile(buffer, 'speech.mp3'),
@@ -32,4 +53,21 @@ async function main() {
3253
console.log(translation.text);
3354
}
3455

35-
main();
56+
/**
57+
* Note, this is Node-specific.
58+
*
59+
* Other runtimes would need a different `fs`,
60+
* and would also use a web ReadableStream,
61+
* which is different from a Node ReadableStream.
62+
*/
63+
async function streamToFile(stream: NodeJS.ReadableStream, path: fs.PathLike) {
64+
return new Promise((resolve, reject) => {
65+
const writeStream = fs.createWriteStream(path).on('error', reject).on('finish', resolve);
66+
67+
// If you don't see a `stream.pipe` method and you're using Node you might need to add `import 'openai/shims/node'` at the top of your entrypoint file.
68+
stream.pipe(writeStream).on('error', (error) => {
69+
writeStream.close();
70+
reject(error);
71+
});
72+
});
73+
}

0 commit comments

Comments
 (0)
Please sign in to comment.