Python:改变音频文件的音高

hil*_*ers 10 python pygame scipy audio-processing

这是我在堆栈上的第一篇文章.到目前为止,这个网站非常有用,但我是一个新手,需要清楚解释我的问题,这与Python中的音调转换音频有关.我安装了当前的模块:numpy,scipy,pygame和scikits"samplerate"api.

我的目标是采用立体声文件,并以尽可能少的步骤以不同的音高播放.目前,我使用pygame.sndarray将文件加载到数组中,然后使用scikits.samplerate.resample应用samplerate转换,然后将输出转换回声音对象以使用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)
Run Code Online (Sandbox Code Playgroud)

kas*_*syc 11

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

>>> snd_array.dtype
dtype('int16')
>>> snd_resample.dtype
dtype('float32')
Run Code Online (Sandbox Code Playgroud)

您可以将resample结果转换为numpy.int16使用astype:

>>> snd_resample = resample(snd_array, 1.5, "sinc_fastest").astype(snd_array.dtype)
Run Code Online (Sandbox Code Playgroud)

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

  • 很高兴看到你喜欢我的回答:)你没有提供任何东西,你的问题很有趣,我也学到了一些东西! (2认同)