2013-03-12 145 views
2

我正在嘗試使用440hz到600hz的音調編寫音頻文件。該文件應該從440hz開始,然後播放每個頻率(按遞增順序)1秒,結束於600hz。我已經提出了python的wave模塊,但是我在這裏做了一些錯誤,因爲我最終沒有聲音的文件。 (如果有人有更好的建議,我真的不在乎它是否在Python中,我使用的是Linux,任何能在該平臺上工作的東西都可以,我只需要創建一個具有上述規格的音頻文件。 !THX)如何編寫多頻音頻文件?

frequencies = range(440,600) 
data_size = len(frequencies) 
fname = "WaveTest.wav" 
frate = 11025.0 # framerate as a float 
amp = 64000.0  # multiplier for amplitude 

sine_list_x = [] 
for f in frequencies: 
    for x in range(data_size): 
     sine_list_x.append(math.sin(2*math.pi*f*(x/frate))) 

wav_file = wave.open(fname, "w") 

nchannels = 1 
sampwidth = 2 
framerate = int(frate) 
nframes = data_size 
comptype = "NONE" 
compname = "not compressed" 

wav_file.setparams((nchannels, sampwidth, framerate, nframes, 
    comptype, compname)) 

for s in sine_list_x: 
    # write the audio frames to file 
    wav_file.writeframes(struct.pack('h', int(s*amp/2))) 

wav_file.close() 

回答

1

像這樣的東西應該工作:希望其至少一個很好的起點,爲您繼續。

import numpy as N 
import wave 

towrite = '' 
for freq in xrange(440,600): 
    duration = 1 
    samplerate = 44100 
    samples = duration*samplerate 
    period = samplerate/float(freq) # in sample points 
    omega = N.pi * 2/period 

    xaxis = N.arange(samples,dtype = N.float) 
    ydata = 16384 * N.sin(xaxis*omega) 

    signal = N.resize(ydata, (samples,)) 

    towrite += ''.join([wave.struct.pack('h',s) for s in signal]) 

f = wave.open('freqs.wav', 'wb') 
f.setparams((1,2,44100, 44100*4, 'NONE', 'noncompressed')) 
f.writeframes(towrite) 
f.close() 

Reference

1

它似乎在Windows。平臺爲我工作得很好:

start of the signal at 440 Hz

end of the signal at 600 Hz

採樣得到尊重和頻率都恰到好處(從440至600Hz)。 但是,在你的代碼中,頻率不會停留一秒鐘,但是對於len(頻率)/ frate-th秒。如果你想每個頻率都有一秒鐘,data_size應該等於frate。

import math 
import wave 
import struct 

frequencies = range(440,600) 
duration = 1 #in second 
fname = "WaveTest.wav" 
frate = 11025.0 # framerate as a float 
amp = 64000.0  # multiplier for amplitude 

sine_list_x = [] 
for f in frequencies: 
    for x in range(duration*frate) : 
     sine_list_x.append(math.sin(2*math.pi*f*(x/frate))) 

wav_file = wave.open(fname, "w") 

nchannels = 1 
sampwidth = 2 
framerate = int(frate) 
nframes = data_size 
comptype = "NONE" 
compname = "not compressed" 

wav_file.setparams((nchannels, sampwidth, framerate, nframes, 
    comptype, compname)) 

for s in sine_list_x: 
    # write the audio frames to file 
    wav_file.writeframes(struct.pack('h', int(s*amp/2))) 

wav_file.close()