我知道以下问题:How to create a pydub AudioSegment using an numpy array?
我的问题正好相反。如果我有一个pydub AudioSegment,我如何将它转换成numpy数组?
我想使用scipy滤镜等等。我不太清楚AudioSegment原始数据的内部结构是什么。
发布于 2016-06-25 04:32:32
Pydub有一个获取audio data as an array of samples的工具,它是一个array.array实例(不是numpy数组),但您应该能够相对容易地将其转换为numpy数组:
from pydub import AudioSegment
sound = AudioSegment.from_file("sound1.wav")
# this is an array
samples = sound.get_array_of_samples()不过,您可以创建该实现的numpy变体。该方法的实现非常简单:
def get_array_of_samples(self):
"""
returns the raw_data as an array of samples
"""
return array.array(self.array_type, self._data)从(修改?)创建新的音频段样本数组也是可能的:
new_sound = sound._spawn(samples)上面的代码有点老生常谈,它是为AudioSegment类内部使用而编写的,但它主要是找出您正在使用的音频数据的类型(样本数组、样本列表、字节、字节串等)。尽管有下划线前缀,但使用它是安全的。
发布于 2017-03-03 06:51:25
您可以从AudioSegment获取array.array,然后将其转换为numpy.ndarray
from pydub import AudioSegment
import numpy as np
song = AudioSegment.from_mp3('song.mp3')
samples = song.get_array_of_samples()
samples = np.array(samples)发布于 2021-04-03 00:23:17
现有的答案没有一个是完美的,它们错过了重塑和样本宽度。我已经编写了这个函数来帮助将音频转换为np中的标准音频表示:
def pydub_to_np(audio: pydub.AudioSegment) -> (np.ndarray, int):
"""
Converts pydub audio segment into np.float32 of shape [duration_in_seconds*sample_rate, channels],
where each value is in range [-1.0, 1.0].
Returns tuple (audio_np_array, sample_rate).
"""
return np.array(audio.get_array_of_samples(), dtype=np.float32).reshape((-1, audio.channels)) / (
1 << (8 * audio.sample_width - 1)), audio.frame_ratehttps://stackoverflow.com/questions/38015319
复制相似问题