使用GStreamer + Python将FLAC转换为MP3?

时间:2011-09-18 03:24:30

标签: python audio gstreamer

这是我试图复制的命令:

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

当我运行此命令时,它运行得很漂亮。我试图使用Pythong绑定来复制它,但根本没有运气。我不会在这些脚本中遇到任何错误,但它们无法正常工作:

当我运行这个脚本时,我只得到一个空的MP3文件:

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

当我运行此脚本时,我收到一个损坏的MP3文件:

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)

任何人都知道我做错了什么?

2 个答案:

答案 0 :(得分:6)

Gstreamer使用GObject作为框架,因此您需要运行gobject.MainLoop()来启动管道中的消息流:

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()

在第二个示例中,您还需要运行MainLoop并链接所有管道元素(例如,使用element_link_many)。 您只将源连接到接收器,因此您的实际管道只是filesrc ! filesink

以下是更正后的代码:

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()

答案 1 :(得分:0)

有些人最终会在这个答案中寻找命令行/ bash解决方案。这是一个很好的转换脚本。

#!/bin/bash

#Take a lossless flac audio track from and transcode it as a constant rate mp3 playable on some older audio equipment that can't play mp4s or variable bit rate mp3's.

if [ -z "$1" ];then
   echo usage: $0 [infile.flac]
   exit
fi

INFILE=$(basename $1)
WKDIR=$(dirname $1)
OUTFILE=$WKDIR/$( echo $INFILE | sed 's/\.flac//').mp3

#play ===================
#gst- launch filesrc location=1.flac \
#! flacdec \
#! autoaudiosink

#transcode ==============
gst-launch filesrc location=$INFILE \
! queue \
! flacdec \
! audioconvert \
! audioresample \
! lamemp3enc quality=2 target=bitrate bitrate=192 cbr=true \
! id3v2mux \
! filesink location=$OUTFILE