Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to transcode mp3 to ogg in python (live)?

I'm searching for a library / module that can transcode an MP3 (other formats are a plus) to OGG, on the fly.

What I need this for: I'm writing a relatively small web app, for personal use, that will allow people to listen their music via a browser. For the listening part, I intend to use the new and mighty <audio> tag. However, few browsers support MP3 in there. Live transcoding seems like the best option because it doesn't waste disk space (like if I were to convert the entire music library) and I will not have performance issues since there will be at most 2-3 listeners at the same time.

Basically, I need to feed it an MP3 (or whatever else) and then get a file-like object back that I can pass back to my framework (flask, by the way) to feed to the client.

Stuff I've looked at:

  • gstreamer -- seems overkill, although has good support for a lot of formats; documentation lacks horribly
  • timeside -- looks nice and simple to use, but again it has a lot of stuff I don't need (graphing, analyzing, UI...)
  • PyMedia -- last updated: 01 Feb 2006...

Suggestions?

like image 205
Felix Avatar asked Mar 28 '11 20:03

Felix


1 Answers

You know, there's no shame in using subprocess to call external utilities. For example, you could construct pipes like:

#!/usr/bin/env python
import subprocess
frommp3 = subprocess.Popen(['mpg123', '-w', '-', '/tmp/test.mp3'], stdout=subprocess.PIPE)
toogg = subprocess.Popen(['oggenc', '-'], stdin=frommp3.stdout, stdout=subprocess.PIPE)
with open('/tmp/test.ogg', 'wb') as outfile:
    while True:
        data = toogg.stdout.read(1024 * 100)
        if not data:
            break
        outfile.write(data)

In fact, that's probably your best approach anyway. Consider that on a multi-CPU system, the MP3 decoder and OGG encoder will run in separate processes and will probably be scheduled on separate cores. If you tried to do the same with a single-threaded library, you could only transcode as fast as a single core could handle it.

like image 139
Kirk Strauser Avatar answered Oct 11 '22 12:10

Kirk Strauser