2011-12-14 107 views
10

這是我的第一篇文章。到目前爲止,這個網站一直非常有幫助,但我是一個新手,需要對我的問題作出清晰的解釋,這與Python中音高改變音頻有關。我安裝了當前模塊:numpy,scipy,pygame和scikits「samplerate」api。Python:更改音頻文件的音高

我的目標是拍攝立體聲文件,並以儘可能少的步驟以不同的音高回放。目前,我使用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) 

回答

10

您的問題是pygame的工作與numpy.int16數組,但調用resample返回numpy.float32陣列:

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

可以resample結果轉換爲numpy.int16使用astype

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

通過此修改,您的python腳本會以較低的音高和較低的速度很好地播放tone.wav文件。

0

最有可能的是scikits.samplerate.resample「思」您的音頻是另一種格式比16位立體聲。檢查scikits.samplerate的文檔,瞭解在陣列中選擇正確的音頻格式的位置 - 如果重新採樣16位音頻,將其視爲8位垃圾。

3

你最好的選擇可能是使用python audiere。

這是一個鏈接,我用它來做同樣的事情,這很容易,只需閱讀所有文檔。

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

+0

謝謝,Audiere是我的第一選擇,但是我無法讓_make_沒有錯誤。我對這個東西不太滿意,所以我必須得到我有限的技能才能完成的工作。 – hilmers 2011-12-16 04:35:09

+0

這看起來不錯,它是否適用於python 2.7?它似乎是爲Python 2.2 – 2013-12-21 22:10:42

0

scikits.samplerate.resample文檔:

如果輸入具有秩1,比所有數據被使用,並且被假定爲從單聲道信號。如果秩爲2,則數字列將被假定爲通道的數量。

所以我認爲你需要做的是這樣的立體數據傳遞到resample中,預計格式:

snd_array = snd_array.reshape((-1,2)) 

snd_resample = resample(snd_array, 1.5, "sinc_fastest") 

snd_resample = snd_resample.reshape(-1) # Flatten it out again 
+0

謝謝。我嘗試了你的建議,但輸出結果相同。 – hilmers 2011-12-20 18:46:05