I’m currently working on the ability to voice text at the click of a button. I have a button that should play text when clicked. I get the audio file through the API after the click, everything works well in this regard, I get the url of the audio file. The problem appears when I try to make this audio work on click. My code now looks something like this:
speech.addEventListener('click', () => {
let speechText = "Привет!";
const audio = new Audio();
const audioURL = await getOpenaiVoice(voiceAPI, voiceID, speechText);
audio.src = audioURL;
audio.play();
}
The code waits for the URL to return from getOpenaiVoice and assigns it to audio.src, but then audio.play(); is triggered instantly, which causes an error: NotSupportedError: Failed to load because no supported source was found.
If you click on the button again after a while, the audio will play normally, because it has already been fully uploaded to the site, and there will be no errors.
I tried to rewrite the code with promises, wrap elements in async await, but I have too little knowledge of asynchronous programming for me to immediately see what the problem is. I’ve been working on this problem all day and I don’t see any options.
function audioLoad(audio, url) {
let prom = new Promise((resolve, reject) => {
audio.src = url;
audio.addEventListener('loadeddata', () => {
resolve(audio);
});
});
prom.then((value) => {
value.play();
})
}
async function audioCreation() {
let speechText = "Привет!";
const audio = new Audio();
const audioURL = await getOpenaiVoice(voiceAPI, voiceID, speechText);
audio.src = audioURL;
audio.play();
}
audioCreation();
The code above works, however, only if you click after the file is fully downloaded. On the first click there are always an error, because it starts downloading only after the click. The general idea is: The user clicks on the voice button, all requests are sent to the API, etc., the code waits for the response to return, and after the response returns, either the audio file starts playing immediately, or it just hangs waiting for full download, and after downloading it starts playing. Thank you in advance.