ElevenLabs text-to-speech API call
Posted: Fri Feb 03, 2023 3:57 pm
This is just a quick procedure for using ElevenLabs to synthesise speech from text. To make it work, you will need to create an account with ElevenLabs and copy the API key that it gives you into this code.
Code: Select all
Procedure.b XI_TTS(api_key.s,voice_id.s,text.s,mp3_fn.s)
If text=""
Debug "XI_TTS: no text specified"
ProcedureReturn #False
EndIf
If voice_id=""
Debug "XI_TTS: no voice_id specified"
ProcedureReturn #False
EndIf
If mp3_fn=""
Debug "XI_TTS: no mp3 file specified"
ProcedureReturn #False
EndIf
u.s = "https://api.elevenlabs.io/v1/text-to-speech/"+voice_id
NewMap header.s()
header("xi-api-key") = api_key
header("accept") = "audio/mpeg"
header("Content-Type") = "application/json"
dat.s = "{ "+#DOUBLEQUOTE$+"text"+#DOUBLEQUOTE$+": "+#DOUBLEQUOTE$+text+#DOUBLEQUOTE$+" }"
req.i = HTTPRequest(#PB_HTTP_Post,u,dat,0,header())
If req
Debug "StatusCode: " + HTTPInfo(req,#PB_HTTP_StatusCode)
Debug "Response: " + HTTPInfo(req,#PB_HTTP_Response)
If HTTPInfo(req,#PB_HTTP_StatusCode)="200"
*ret = HTTPMemory(req)
Debug "Response size: " + MemorySize(*ret)
f = CreateFile(#PB_Any,mp3_fn)
WriteData(f,*ret,MemorySize(*ret))
CloseFile(f)
FreeMemory(*ret)
EndIf
FinishHTTP(req)
ProcedureReturn #True
EndIf
EndProcedure
#VoiceID_Rachel = "21m00Tcm4TlvDq8ikWAM" ; American, mellow
#VoiceID_Domi = "AZnzlk1XvdvUeBnXmlld" ; American, engaged
#VoiceID_Bella = "EXAVITQu4vr4xnSDxMaL" ; American, soft
#VoiceID_Antoni = "ErXwobaYiN019PkySvjV" ; American, modulated
#VoiceID_Elli = "MF3mGyEYCl7XYWbV9V6O" ; American, clear
#VoiceID_Josh = "TxGEqnHWrfWFTfGW9XjX" ; American, silvery
#VoiceID_Arnold = "VR6AewLTigWG4xSOukaG" ; American, nasal
#VoiceID_Adam = "pNInz6obpgDQGcFmaJgB" ; American, clear
#XIApiKey = "" ; insert your API key here
mp3_fn.s = "P:\xi-response.mp3" ; a file location here
txt.s = "my ElevenLabs text"
If XI_TTS(#XIApiKey,#VoiceID_Antoni,txt,mp3_fn)
RunProgram(mp3_fn)
EndIf