我希望我能找到一种方法从 python 中的 mp3 中获取振幅数据。与 audacity 类似,但我不想要视觉效果,一个简单的值数组就可以了。当声音变大时,我希望我的代码在某些时候对声音使用react。我正在使用 pygame 播放音频并试图将其转换为 sndarray 但它只给了我前 0.00018 秒。不管怎样,我可以得到整个 mp3 吗?它不一定是实时的,因为无论如何我都希望能够提前使用react,并且会使用 pygame 跟踪我的位置。
我正在 build this cloud使用树莓派代替其他功能。我已经有了照明工作,需要它对闪电使用react,遗憾的是 lightshowpi 不是一个选择。任何帮助将不胜感激
编辑: 这就是我到目前为止所拥有的,感谢 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)
请您参考如下方法:
使用 pydub , 你可以很容易地得到 mp3 文件的 loudness 和 highest amplitude 。然后,您可以使用这些参数之一来使代码/光对此使用react。
来自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 为单位返回 AudioSegment 的响度(db 相对于最大可能响度)。最大幅度的方波大约为 0 dBFS(最大响度),而最大幅度的正弦波大约为 -3 dBFS。
from pydub import AudioSegment
sound = AudioSegment.from_file("/path/to/sound.mp3", format="mp3")
loudness = sound.dBFS
