如何编写多频率音频文件?

2 投票
2 回答
1090 浏览
提问于 2025-04-17 18:52

我想制作一个音频文件,里面的音调从440赫兹到600赫兹。这个文件应该从440赫兹开始,然后每个频率播放1秒钟,最后以600赫兹结束。我尝试使用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()

2 个回答

1

在我的Windows系统上,这个看起来运行得很好:

信号开始于440 Hz

信号结束于600 Hz

采样是符合要求的,频率也正好(从440到600 Hz)。不过,在你的代码里,频率并没有持续一秒,而是持续了len(frequencies)/frate秒。如果你想让每个频率都持续一整秒,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()
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()

参考链接

撰写回答