这是我在堆栈上的第一篇文章。到目前为止,这个网站一直很有帮助,但我是一个新手,需要对我的问题有一个清晰的解释,这个问题与 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')
您可以使用 astype
将 resample
结果转换为 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/