Writing .mp3 file directly from stream

4.8k Views Asked by At

I'm trying to record samples from a stream and save the snippets as an .mp3 file. The following code properly reads the stream and saves the data to the file. The file plays in a media player but it has no headers, etc., so when I try and do something else with the .mp3 file (such as converting it to another format using LAME), it fails every time. Does anyone have any experience with this sort of thing?

Below is a working example to get the .mp3 file. Sorry if you get a commercial; radio sucks.

import urllib2
from datetime import datetime
from datetime import timedelta

# Name of the file stream and how long to record a sample
URL = "http://4893.live.streamtheworld.com:80/KUFXFMAAC_SC"
RECORD_SECONDS = 30

# Open the file stream and write file
filename = 'python.mp3'
f=file(filename, 'wb')
url=urllib2.urlopen(URL)

# Basically a timer
t_start = datetime.now()
t_end = datetime.now()
t_end_old = t_end

# Record in chunks until
print "Recording..."
while t_end-t_start < timedelta(seconds=RECORD_SECONDS):
    f.write(url.read(1024))
    t_end = datetime.now()
# Or one big read?
#f.write(url.read(1024*517))


f.close()

This is maybe close to what I'm trying to do:? encoding mp3 from a audio stream of PyTTS

1

There are 1 best solutions below

5
On

You need to read about mpeg frames http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm You are likely not lining up the frames when you capture, so your first and last frames are probably incomplete.

The beginning of a frame is 11 set bit's, so 11 ones in a row. So you need to find the start of the first frame and remove everything before it, then find the start of the last frame and remove it. Or you could do it while reading from the stream. You can use binascii to check the hex values.