Python改变音频文件的音调

2024-05-16 19:40:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在堆栈上的第一篇文章。到目前为止,这个网站非常有帮助,但我是一个新手,需要一个清晰的解释我的问题,这是有关音高转换在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)

Tags: andnumpymake音频arraypygamefileresample
3条回答

你的问题是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 audiere。

这里有一个链接,我用它来做同样的事情,很简单,只要阅读所有的文档。

http://audiere.sourceforge.net/home.php

很可能scikits.samplerate.resample“认为”您的音频不是16位立体声格式。查看scikits.samplerate上的文档,了解在阵列中选择正确音频格式的位置- 如果它重新采样16位音频,将其作为8位垃圾处理是什么会出来。

相关问题 更多 >