简体   繁体   English

使用python从mp3音频文件中获取振幅数据

[英]get the amplitude data from an mp3 audio files using python

I have an mp3 file and I want to basically plot the amplitude spectrum present in that audio sample. 我有一个mp3文件,我想基本上绘制出该音频样本中存在的振幅频谱。 I know that we can do this very easily if we have a wav file. 我知道如果我们有一个wav文件,我们可以很容易地做到这一点。 There are lot of python packages available for handling wav file format. 有很多python软件包可用于处理wav文件格式。 However, I do not want to convert the file into wav format then store it and then use it. 但是,我不想将文件转换为wav格式,然后存储然后使用。 What I am trying to achieve is to get the amplitude of an mp3 file directly and even if I have to convert it into wav format, the script should do it on air during runtime without actually storing the file in the database. 我要实现的目标是直接获取mp3文件的幅度,即使我必须将其转换为wav格式,脚本也应该在运行时进行广播,而无需实际将文件存储在数据库中。 I know we can convert the file like follows: 我知道我们可以像下面这样转换文件:

from pydub import AudioSegment
sound = AudioSegment.from_mp3("test.mp3")
sound.export("temp.wav", format="wav")

and it creates the temp.wav which it supposed to but can we just use the content without storing the actual file? 并创建了预期的temp.wav,但是我们可以仅使用内容而不存储实际文件吗?

MP3 is encoded wave (+ tags and other stuff). MP3是已编码的wave(+标签和其他内容)。 All you need to do is decode it using MP3 decoder. 您需要做的就是使用MP3解码器对其进行解码。 Decoder will give you whole audio data you need for further processing. 解码器将为您提供需要进一步处理的完整音频数据。

How to decode mp3? 如何解码mp3? I am shocked there are so few available tools for Python. 令我震惊的是,几乎没有可用的Python工具。 Although I found a good one in this question. 虽然我在这个问题上找到了一个很好的人。 It's called pydub and I hope I can use a sample snippet from author (I updated it with more info from wiki): 它叫做pydub ,我希望我可以使用作者提供的示例代码片段(我用wiki的更多信息更新了它):

from pydub import AudioSegment

sound = AudioSegment.from_mp3("test.mp3")

# get raw audio data as a bytestring
raw_data = sound.raw_data
# get the frame rate
sample_rate = sound.frame_rate
# get amount of bytes contained in one sample
sample_size = sound.sample_width
# get channels
channels = sound.channels

Note that raw_data is 'on air' at this point ;). 请注意,此时raw_data处于“播放中”状态;)。 Now it's up to you how do you want to use gathered data, but this module seems to give you everything you need. 现在由您决定如何使用收集的数据,但是此模块似乎可以为您提供所需的一切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM