Skip to content

Commit

Permalink
docs: improve audio example to show how to stream to a file (#598)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot committed Jan 9, 2024
1 parent b595cd9 commit 8165725
Showing 1 changed file with 41 additions and 3 deletions.
44 changes: 41 additions & 3 deletions examples/audio.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env -S npm run tsn -T
import 'openai/shims/node';

import OpenAI, { toFile } from 'openai';
import fs from 'fs/promises';
import fs from 'fs';
import path from 'path';

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

async function main() {
await streamingDemoNode();
await blockingDemo();
}
main();

async function streamingDemoNode() {
const response = await openai.audio.speech.create({
model: 'tts-1',
voice: 'alloy',
input: 'the quick brown chicken jumped over the lazy dogs',
});

const stream = response.body;

console.log(`Streaming response to ${speechFile}`);
await streamToFile(stream, speechFile);
console.log('Finished streaming');
}

async function blockingDemo() {
const mp3 = await openai.audio.speech.create({
model: 'tts-1',
voice: 'alloy',
input: 'the quick brown fox jumped over the lazy dogs',
});

const buffer = Buffer.from(await mp3.arrayBuffer());
await fs.writeFile(speechFile, buffer);
await fs.promises.writeFile(speechFile, buffer);

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

main();
/**
* Note, this is Node-specific.
*
* Other runtimes would need a different `fs`,
* and would also use a web ReadableStream,
* which is different from a Node ReadableStream.
*/
async function streamToFile(stream: NodeJS.ReadableStream, path: fs.PathLike) {
return new Promise((resolve, reject) => {
const writeStream = fs.createWriteStream(path).on('error', reject).on('finish', resolve);

// 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.
stream.pipe(writeStream).on('error', (error) => {
writeStream.close();
reject(error);
});
});
}

0 comments on commit 8165725

Please sign in to comment.