2013-03-12 147 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()