如何从pydub AudioSegment创建一个numpy数组? [英] How to create a numpy array from a pydub AudioSegment?

查看:475
本文介绍了如何从pydub AudioSegment创建一个numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以下问题: 如何使用numpy数组创建pydub AudioSegment?

I'm aware of the following question: How to create a pydub AudioSegment using an numpy array?

我的问题是恰好相反.如果我有pydub AudioSegment,如何将其转换为numpy数组?

My question is the right opposite. If I have a pydub AudioSegment how can I convert it to a numpy array?

我想使用scipy过滤器等. 我不太清楚AudioSegment原始数据的内部结构是什么.

I would like to use scipy filters and so on. It is not very clear to me what is the internal structure of the AudioSegment raw data.

推荐答案

Pydub具有获取

Pydub has a facility for getting the audio data as an array of samples, it is an array.array instance (not a numpy array) but you should be able to convert it to a numpy array relatively easily:

from pydub import AudioSegment
sound = AudioSegment.from_file("sound1.wav")

# this is an array
samples = sound.get_array_of_samples()

您也许可以创建该实现的numpy变体.该方法的实现非常简单:

You may be able to create a numpy variant of the implementation though. That method is implemented pretty simply:

def get_array_of_samples(self):
    """
    returns the raw_data as an array of samples
    """
    return array.array(self.array_type, self._data)

也可以通过(修改的?)样本数组创建新的音频片段:

Creating a new audio segment from a (modified?) array of samples is also possible:

new_sound = sound._spawn(samples)

上面的代码有点怪异,它是为在AudioSegment类中内部使用而编写的,但是它主要只是弄清楚您正在使用哪种类型的音频数据(样本数组,样本列表,字节,字节串等). ).尽管有下划线前缀,但仍可以安全使用.

The above is a little hacky, it was written for internal use within the AudioSegment class, but it mainly just figures out what type of audio data you're using (array of samples, list of samples, bytes, bytestring, etc). It's safe to use despite the underscore prefix.

这篇关于如何从pydub AudioSegment创建一个numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆