Python:改变音频文件的音高

标签 python scipy pygame audio-processing

这是我在堆栈上的第一篇文章。到目前为止,这个网站一直很有帮助,但我是一个新手,需要对我的问题有一个清晰的解释,这个问题与 Python 中的音高转换音频有关。我安装了当前模块:numpy、scipy、pygame 和 scikits“samplerate”api。

我的目标是获取一个立体声文件并以尽可能少的步骤以不同的音高播放它。目前,我使用 pygame.sndarray 将文件加载到数组中,然后使用 scikits.samplerate.resample 应用采样率转换,然后使用 pygame 将输出转换回声音对象以进行播放。问题是我的扬声器发出垃圾音频。我当然错过了一些步骤(除了对数学和音频一无所知之外)。

谢谢。

import time, numpy, pygame.mixer, pygame.sndarray
from scikits.samplerate import resample

pygame.mixer.init(44100,-16,2,4096)

# choose a file and make a sound object
sound_file = "tone.wav"
sound = pygame.mixer.Sound(sound_file)

# load the sound into an array
snd_array = pygame.sndarray.array(sound)

# resample. args: (target array, ratio, mode), outputs ratio * target array.
# this outputs a bunch of garbage and I don't know why.
snd_resample = resample(snd_array, 1.5, "sinc_fastest")

# take the resampled array, make it an object and stop playing after 2 seconds.
snd_out = pygame.sndarray.make_sound(snd_resample)
snd_out.play()
time.sleep(2)

最佳答案

你的问题是 pygame 使用 numpy.int16 数组,但是调用 resample 返回一个 numpy.float32 数组:

>>> snd_array.dtype
dtype('int16')
>>> snd_resample.dtype
dtype('float32')

您可以使用 astyperesample 结果转换为 numpy.int16:

>>> snd_resample = resample(snd_array, 1.5, "sinc_fastest").astype(snd_array.dtype)

通过此修改,您的 Python 脚本可以很好地播放 tone.wav 文件,音调和速度都较低。

关于Python:改变音频文件的音高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8501141/

相关文章:

python - 如何在 Matplotlib 中绘制模糊点

python - 从URL上传Django ImageField

python - 我试图在无摩擦的地板上模拟一个质量,并用 Spring 固定在一端。不工作

python - 如何获得高标准差基于时间的数据的置信区间?

python - pygame - 如何从 get_pos 中拆分 X 和 Y 坐标

python - 无法触发颜色上的鼠标按下事件

python - 无法使用 ffmpeg 从 mp4 文件创建音频文件

python - PySpark:写入时吐出单个文件而不是多个部分文件

python - 检测矩阵中的对角线

python - 在 Mountain Lion 上安装 Pygame 时出错