如何编写多频音频文件?

时间:2013-03-12 22:55:42

标签: python linux audio wav

我正在尝试用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()

2 个答案:

答案 0 :(得分: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 :(得分:1)

在Windows平台上,它似乎对我有用:

start of the signal at 440 Hz

end of the signal at 600 Hz

采样得到尊重,频率恰到好处(从440到600 Hz)。 但是,在你的代码中,频率不会停留一秒钟,而是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()