A hacky way to display audio tranlations from Google Translate

Problem

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.

Solution

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 tranlation 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 content-type: audio/mpeg:

Find the audio network request
Find the audio request

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:

How Hello World sounds in Greek:

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

Popular posts

Other notes