AcerWolf
AcerWolf

Reputation: 25

How to download mpeg/mp3 with Python?

I have this link:
https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&q=dog&tl=en&total=1&idx=0&textlen=3
I can download the audio manually by right-click → "Save Audio As..." and then saving it as .mp3
How is it possible to download it with a Python Script?

right click on player

Upvotes: 1

Views: 1178

Answers (2)

Paul M.
Paul M.

Reputation: 10799

You can do this with the third-party requests module:

def main():

    import requests

    url = "https://translate.google.com/translate_tts"

    text = "dog"

    params = {
        "ie": "UTF-8",
        "client": "tw-ob",
        "q": text,
        "tl": "en",
        "total": "1",
        "idx": "0",
        "textlen": str(len(text))
    }

    response = requests.get(url, params=params)
    response.raise_for_status()

    assert response.headers["Content-Type"] == "audio/mpeg"

    with open("output.mp3", "wb") as file:
        file.write(response.content)

    print("Done.")
    
    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

Upvotes: 3

JaSON
JaSON

Reputation: 4869

This code should allow you to save required content as MP3:

import requests

url = 'https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&q=dog&tl=en&total=1&idx=0&textlen=3'
response = requests.get(url)

with open('/path/to/file/qwerty.mp3', 'wb') as f:
    f.write(response.content)

Upvotes: 0

Related Questions