2016-05-16 133 views
0

我希望能找到一种方法从python中获取mp3中的振幅数据。与大胆类似,但我不想要一个可视化的,简单的数组值。我希望我的代码在声音变得响亮时在某些点响应声音。我使用pygame来播放音频,并试图将其转换为sndarray,但它只给了我第一个0.00018秒。无论如何,我可以得到整个MP3?它不一定是实时的,因为我希望能够提前做出反应,并会使用pygame跟踪我的位置。Python - 获取mp3的波形/振幅

我使用的是树莓派,而不是对其他功能建设this cloud。我已经有了照明工作,需要它对闪电做出反应,可惜的是Lightshowpi不是一种选择。任何帮助将不胜感激

编辑: 所以这是我至今感谢编唐。它的工作原理,但我挂在while循环。我不知道为什么。我使用的MP3相当长,这可能是问题吗?

import os, sys 
from gi.repository import Gst, GObject 
Gst.init() 
GObject.threads_init() 

def get_peaks(filename): 
global do_run 

pipeline_txt = (
    'filesrc location="%s" ! decodebin ! audioconvert ! ' 
    'audio/x-raw,channels=1,rate=22050,endianness=1234,' 
    'width=32,depth=32,signed=(bool)TRUE !' 
    'level name=level interval=1000000000 !' 
    'fakesink' % filename) 
pipeline = Gst.parse_launch(pipeline_txt) 

level = pipeline.get_by_name('level') 
bus = pipeline.get_bus() 
bus.add_signal_watch() 

peaks = [] 
do_run = True 

def show_peak(bus, message): 
    global do_run 
    if message.type == Gst.MESSAGE_EOS: 
     pipeline.set_state(Gst.State.NULL) 
     do_run = False 
     return 
    # filter only on level messages 
    if message.src is not level or \ 
     not message.structure.has_key('peak'): 
     return 
    peaks.append(message.structure['peak'][0]) 

# connect the callback 
bus.connect('message', show_peak) 

# run the pipeline until we got eos 
pipeline.set_state(Gst.State.PLAYING) 
ctx = GObject.MainContext() 
while ctx and do_run: 
    ctx.iteration() 

return peaks 

def normalize(peaks): 
    _min = min(peaks) 
    print(_min) 
    _max = max(peaks) 
    print(_max) 
    d = _max - _min 
    return [(x - _min)/d for x in peaks] 

if __name__ == '__main__': 
    filename = os.path.realpath(sys.argv[1]) 
    peaks = get_peaks(filename) 

    print('Sample is %d seconds' % len(peaks)) 
    print('Minimum is', min(peaks)) 
    print('Maximum is', max(peaks)) 

    peaks = normalize(peaks) 
    print(peaks) 
+0

我觉得这个已经被问已经 - http://stackoverflow.com/questions/9344888/getting-max-amplitude-for-an-audio-file-per-second?lq=1 HTTP: //stackoverflow.com/questions/10304495/python-getting-the-amplitudes-of-a-sound-file –

回答

0

使用pydub,你可以得到一个mp3文件loudnesshighest amplitude变得非常容易。然后,您可以使用这些参数中的一个来使代码/指示灯对此作出反应。

pydub网站,

AudioSegment(...)。最大

在AudioSegment任何样本的最高幅度。对标准化(在pydub.effects.normalize中提供的)有用。

from pydub import AudioSegment 
sound = AudioSegment.from_file("/path/to/sound.mp3", format="mp3")  
peak_amplitude = sound.max 

AudioSegment(...).dBFS

返回AudioSegment在dBFS的(相对于最大可能的音量分贝)的响度。最大幅度处的方波大致为0 dBFS(最大响度),而最大幅度处的正弦波大约为-3 dBFS。

from pydub import AudioSegment 
sound = AudioSegment.from_file("/path/to/sound.mp3", format="mp3") 
loudness = sound.dBFS