Skip to content

Instantly share code, notes, and snippets.

@magician11
Last active August 3, 2023 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magician11/a80dff28c2edee2d64dc66b0e7431a11 to your computer and use it in GitHub Desktop.
Save magician11/a80dff28c2edee2d64dc66b0e7431a11 to your computer and use it in GitHub Desktop.
Playing audio generated from ElevenLabs in frontend JavaScript
import axios from 'axios';
const playAudio = async ({ text, voiceId }) => {
const response = await axios.post(
`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`,
{ text },
{
headers: {
'Content-Type': 'application/json',
'xi-api-key': process.env.REACT_APP_ELEVENLABS_API_KEY
},
responseType: 'blob'
}
);
const audio = new Audio(URL.createObjectURL(response.data));
audio.play();
await new Promise(resolve => {
audio.addEventListener('ended', () => {
resolve();
});
});
};
export { playAudio };
@magician11
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment