Python - 获取mp3的波形/幅度

时间:2016-05-16 00:36:12

标签: python audio mp3

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

我正在使用覆盆子pi构建this cloud而不是其他功能。我已经有了照明工作,需要它对闪电做出反应,光影显示不是一个可悲的选择。任何帮助将不胜感激

编辑: 所以这就是我迄今为止感谢coder-don。它工作,但我挂在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)

1 个答案:

答案 0 :(得分:1)

使用pydub,您可以非常轻松地获取loudness文件的highest amplitudemp3。然后,您可以使用其中一个参数来使代码/光响应。

来自pydub网站

<强> AudioSegment(...)的.max

AudioSegment中任何样本的最高幅度。适用于规范化(在pydub.effects.normalize中提供)。

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

<强> AudioSegment(...).dBFS

以dBFS(db相对于最大可能响度)返回AudioSegment的响度。最大振幅的方波大约为0 dBFS(最大响度),而最大振幅的正弦波大约为-3 dBFS。

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