Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert FLAC to MP3 with GStreamer + Python?

Here's the command I'm trying to replicate:

gst-launch filesrc location=test.flac ! flacdec ! lame ! filesink location=test.mp3

When I run this command it works beautifully. I've tried to replicate this using the Pythong bindings with no luck at all. I don't get any errors with either of these scripts, but they don't work as expected:

When I run this script I just get an empty MP3 file:

import gst
pipeline = gst.parse_launch('filesrc location="test.flac" ! flacdec ! lame ! filesink location="test.mp3"')
pipeline.set_state(gst.STATE_PLAYING)

When I run this script I get a corrupt MP3 file:

import gst

converter = gst.Pipeline('converter')

source = gst.element_factory_make('filesrc', 'file-source')
source.set_property('location', 'test.flac')

decoder = gst.element_factory_make('flacdec', 'decoder')

encoder = gst.element_factory_make('lame', 'encoder')

sink = gst.element_factory_make('filesink', 'sink')
sink.set_property('location', 'test.mp3')

converter.add(source, decoder, encoder, sink)

source.link(sink)

converter.set_state(gst.STATE_PLAYING)

Anyone know what I'm doing wrong?

like image 806
Liam Avatar asked Aug 27 '26 18:08

Liam


1 Answers

Gstreamer uses GObject as a framework, so you need to run gobject.MainLoop() to start message flow in pipeline:

import gobject
import gst
pipeline = gst.parse_launch('filesrc location="test.flac" ! flacdec ! lame ! filesink location="test.mp3"')
pipeline.set_state(gst.STATE_PLAYING)

gobject.threads_init()
gobject.MainLoop().run()

In the second example you also need to run MainLoop and link all the pipeline elements (e.g. with element_link_many). You connected only source to sink, so your actual pipeline is just filesrc ! filesink.

Here is corrected code:

import gobject
import gst

converter = gst.Pipeline('converter')

source = gst.element_factory_make('filesrc', 'file-source')
source.set_property('location', 'test.flac')

decoder = gst.element_factory_make('flacdec', 'decoder')
encoder = gst.element_factory_make('lame', 'encoder')

sink = gst.element_factory_make('filesink', 'sink')
sink.set_property('location', 'test.mp3')

converter.add(source, decoder, encoder, sink)
gst.element_link_many(source, decoder, encoder, sink)

converter.set_state(gst.STATE_PLAYING)

gobject.threads_init()
gobject.MainLoop().run()
like image 88
max taldykin Avatar answered Aug 29 '26 10:08

max taldykin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!