import fs from "fs";
import path from "path";
import OpenAI from "openai";
import dotenv from "dotenv";
dotenv.config();
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
throw new Error("OpenAI API key not found. Please ensure it's set in your environment variables.");
}
const openai = new OpenAI({ apiKey });
const speechFile = path.resolve("./speech.mp3");
export default async function tts() {
try {
const mp3 = await openai.audio.speech.create({
model: "tts-1",
voice: "alloy",
input: "Today is a wonderful day to build something people love!",
});
console.log(speechFile);
const buffer = Buffer.from(await mp3.arrayBuffer());
await fs.promises.writeFile(speechFile, buffer);
} catch (error) {
console.error("Error:", error);
throw error; // Re-throw the error to propagate it
}
}
When trying out this code I keep getting the following error, I haven't found a working solution yet:
file:///D:/Documenten/Toegepaste%20Informatica/2023-2024/Stage/demo/tts/modules/tts.mjs:20
const mp3 = await openai.audio.speech.create({
^
TypeError: Cannot read properties of undefined (reading 'create')
at tts (file:///D:/Documenten/Toegepaste%20Informatica/2023-2024/Stage/demo/tts/modules/tts.mjs:20:47)
at file:///D:/Documenten/Toegepaste%20Informatica/2023-2024/Stage/demo/tts/index.mjs:3:1
at ModuleJob.run (node:internal/modules/esm/module_job:195:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:336:24)
at async loadESM (node:internal/process/esm_loader:34:7)
at async handleMainPromise (node:internal/modules/run_main:106:12)