2

我正在尝试使用 440hz 到 600hz 的音调编写音频文件。该文件应从 440hz 开始,然后播放每个频率(按递增顺序)1 秒,以 600hz 结束。我想出了python的wave模块,但是在这里做错了,因为我最终得到了一个没有声音的文件。(如果有人有更好的建议,我真的不在乎它是否在 python 中。我正在使用 Linux,任何可以在该平台上运行的东西都可以。我只需要创建一个具有上述规格的音频文件。谢谢!)

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()
4

2 回答 2

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()

参考

于 2013-03-12T23:19:52.093 回答
1

它在 Windows 平台上对我来说似乎工作正常:

440 Hz 信号开始

600 Hz 信号结束

采样得到尊重,频率恰到好处(从 440 到 600 Hz)。但是,在您的代码中,频率不会停留一秒钟,而是停留在 len(frequencies)/frate-th of second。如果您希望每个频率都有一整秒,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()
于 2013-03-12T23:32:37.040 回答