'How to render an audio file from an API in React
I have a dictionary API that has a pronounciation feature (?). Here's an example with the word city "https://api.dictionaryapi.dev/media/pronunciations/en/city-us.mp3"
I have no idea how i can render it. I thought it was something like
const [input, setInput] = useState("");
const soundApi = async () => {
try {
const soundData = await axios.get(
`https://api.dictionaryapi.dev/media/pronunciations/en/${input}-us.mp3`
);
console.log(soundData);
} catch (error) {}
};
And then the useEffect below it
useEffect(() => {
dictionaryApi();
soundApi();
}, [input]);
Solution 1:[1]
If you want to render a audio element you can go like this
<audio
controls
src="https://api.dictionaryapi.dev/media/pronunciations/en/city-us.mp3"
>
Your browser does not support the
<code>audio</code> element.
</audio>
I'm not sure if I understood correctly, but there is no need to fetch this url in order to display audio elements
Solution 2:[2]
How Damian Busz said, its not necessary an api request to get audio file. But, Suposing that you need authentication for get this audio, and is using axios to get it, you could do the follow:
const [audioURI, setAudioURI] = useState("");
const [input, setInput] = useState("");
const soundApi = async () => {
try {
const response = await axios.get({
url: `https://api.dictionaryapi.dev/media/pronunciations/en/${input}-us.mp3`,
method: 'GET',
responseType: 'blob',
});
// This will create a Local URL that can be used on an audio source
const audioUrl = window.URL.createObjectURL(new Blob([response.data]));
setAudioURI(audioUrl);
console.log(soundData);
} catch (error) {}
};
In your audio component:
{!!audioURI && (
<audio controls src={audioURI}>
Your browser does not support the
<code>audio</code> element.
</audio>
)}
You can also return the URL value from the soundAPI functio
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Damian Busz |
| Solution 2 | Nero |
