Search code examples
pythonpython-3.xaudiomp3raw-data

Play mp3 raw audio data without writing to file


I would like to know how I can play mp3 raw audio data (retrieved from Ivona text to speech API) without writing it to a file.

Does I have to convert it to wav and use pyaudio?


Solution

  • Here's a way to do it:

    from urllib.request import urlopen
    import pyaudio
    
    pyaud = pyaudio.PyAudio()
    srate=44100
    stream = pyaud.open(format = pyaud.get_format_from_width(1),
                    channels = 1,
                    rate = srate,
                    output = True)
    
    
    url = ... # Assuming you retrive audio data from an URL
    u = urlopen(url)
    data = u.read(8192)
    
    while data:
        stream.write(data)
        data = u.read(8192)
    

    For reference, see How to play mp3 from URL.

    Hope this helps!