A hacky way to display audio translations from Google Translate
You want to display an audio translation of a word or phrase in your HTML page and you’re not sure how. You first thought is to use Google Translate. So you search for a Google Translate widget that would allow you to add a phrase, a target language, and then hear the translation, but you find none. Well, at least for the 5 minutes you searched.
If Google Translate doesn’t give you a widget, you’ll take the audio file by force, using the developer tools, and display it in a simple HTML audio tag. Needless to say that’s probably a violation of the terms of service, and you should use it only on a personal project.
For this example, I want to translate the
"Hello World!" string to Greek. I go to Google Translate and I configure the UI. I can now hear the translation if I press the speaker button, so there must be an audio file my browser downloaded.
Open your Chrome DevTools to find out. Navigate to the network tab and press the speaker button again in the UI. You see a bunch of requests popping out, but you are interested in one with
Right click on the network request and select Copy -> Copy Response from the context menu. You now have an inline audio string in your clipboard. This string is really long and you probably don’t want it inside your markup, so you should better store it in a different file, a JSON file for example. Let’s now create the HTML audio tag to display it:
<figure> <figcaption>How Hello World sounds in Greek:</figcaption> <audio controls src="data:audio/mpeg;base64,//NAxAATqVJAAEoGcCeiAAgYYQIM....." > Your browser does not support the <code>audio</code> element. </audio> </figure>
And this is what it looks like:
If you want to translate something bigger than a word or a phrase, a big sentence or a paragraph for example, Google Translate will break down the audio into multiple files. As a result, this method won’t help you much, it’s better suited for small text.
Other things to read
- Reveal animations on scroll with react-spring
- Gatsby background image example
- Extremely fast loading with Gatsby and self-hosted fonts