Writing to wav file from a stream has no audio data

Viewed 212

I'm working on creating a wav file from a stream on iheartradio. I am able to get the stream url, but once I write the data to a wav file, I cannot play it on any media player I've tried. I don't have experience with wav files too much so any help would be greatly appreciated. This is what I've got so far from looking at similar posts:

import requests

stream_url = "http://stream.revma.ihrhls.com/zc2525"

r = requests.get(stream_url, stream=True)

with open('stream.wav', 'wb') as f:
    try:
        for block in r.iter_content(1024):
            f.write(block)
            print(block)
    except KeyboardInterrupt:
        f.close()
2 Answers

I've tested your code, and it seems to be working. I have no issue at all. The issue must be your audio player. Have you tested it with a wav file you know is working?

You're making the assumption that the response contains a WAV header followed by PCM (Pulse Code Modulated) samples. That's not the case. If you print the response headers, you'll see that the response contains AAC (Advanced Audio Coding) audio data, which is a lossy compressed audio format - totally different from lossless WAV. AAC is pretty standard for internet radio streams.

That being said, your code works fine for me, and the generated ".wav" file does play in my Windows 10 Windows Media Player / VLC. However, Just because you gave your file the ".wav" extension, doesn't mean it's actually a WAV file. It could just be that your media players are more pedantic than mine, and refuse to play files where there's a discrepancy between the file's headers and the file's extension. My media players seem to ignore the extension, and attempt to determine the format by inspecting the file headers - you could even rename it to stream.mp3 or stream.foobar, and it will play just the same. Again, the file extensions don't really matter, what matters is the actual data (headers and samples) that you write to the file. Don't assume that everything is a WAV file.

Related