-1

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

Community
  • 1
  • 1
Radical Edward
  • 5,234
  • 5
  • 21
  • 33
  • Right now, all you are getting is a raw stream (which wont have any headers). So theoretically, you can name the file `python.wav`, `python.wma` and it will probably be correctly read. I'm not exactly sure how mp3s are encoded from bytecode, but you will need to "wrap" the bytecode with the mp3 shell. – Matt R Dec 10 '13 at 20:28
  • As a followup, check out [PyMedia](http://pymedia.org/index.html) to create the MP3 for you. – Matt R Dec 10 '13 at 20:37
  • I couldn't get pymedia to work for this applicaiton. I tried just changing the extension to .wav but I still have the same problem. – Radical Edward Dec 10 '13 at 22:27
  • @RadicalEdward For what it's worth, I've dumped many streams this way and have never had a problem with FFMPEG converting them. FFMPEG is **very** tolerant of errors. There's a switch to configure its behavior, but I don't remember it. You might also try a different FFmpeg build. – Brad Dec 11 '13 at 20:29

1 Answers1

0

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.

AronVietti
  • 369
  • 2
  • 6