我最近开始用EXPO开发一款Reaction Native App,几天前我遇到了一个问题,现在开始让我发疯.
我想向OpenAI TTS API发送一个文本字符串,并立即在我的应用程序中播放音频响应.我不想将文件保存在本地.接口链接:https://platform.openai.com/docs/guides/text-to-speech
到目前为止,我已经成功地发出了HTTP请求,看起来我从API得到了正确的响应.当我输出response.blob()
时,我得到:
{"_data": {"__collector": {}, "blobId": "5C362F63-71CB-45EC-913E-9A808AF2194F", "name": "speech.mp3", "offset": 0, "size": 143520, "type": "audio/mpeg"}}
个
这个问题似乎是播放声音与AV.我已经在谷歌上搜索了好几天了,无论我try 哪种解决方案,我在try 播放声音时都会遇到一些错误.当前代码的当前错误是:
错误:AVPlayerItem实例失败,错误代码为-1002,域为"NSURLErrorDOMAIN".
如果有人能帮我(请写代码示例),我将不胜感激.
我还读到了这篇文章,其中的解决方案是改用谷歌的TTS API,但这不是我想要的解决方案: https://www.reddit.com/r/reactnative/comments/13pa9wx/playing_blob_audio_using_expo_audio_react_native/ 个
这是我的代码:
const convertTextToSpeech = async (textToConvert) => {
const apiKey = 'myKey';
const url = 'https://api.openai.com/v1/audio/speech';
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'tts-1',
input: textToConvert,
voice: 'alloy',
language: 'da',
})
};
await fetch(url, requestOptions)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.blob();
})
.then(blob => {
playSound(blob);
})
.catch(error => {
console.error('There was a problem with the request:', error);
});
};
async function playSound(blob) {
const url = URL.createObjectURL(blob);
const { sound } = await Audio.Sound.createAsync({ uri: url });
await sound.playAsync();
}