如何用Ruby或Python创建一系列高低音的哔声?
我想要在固定的时间间隔内,制作一系列高音和低音的哔声。比如:
- 在150毫秒时发出高音哔声
- 在151毫秒时发出低音哔声
- 在200毫秒时发出低音哔声
- 在250毫秒时发出高音哔声
请问在Ruby或Python中,有什么方法可以做到这一点吗?我对输出文件的格式(.wav、.mp3、.ogg等)没有特别要求,但我确实想要生成一个输出文件。
5 个回答
4
这里有一个用Python写的函数,它可以生成一个包含单一正弦波的文件:
# based on : www.daniweb.com/code/snippet263775.html
import math
import wave
import struct
def make_sine(freq=440, datasize=10000, fname="test.wav", framerate=44100.00):
amp=8000.0 # amplitude
sine_list=[]
for x in range(datasize):
sine_list.append(math.sin(2*math.pi * freq * ( x/frate)))
# Open up a wav file
wav_file=wave.open(fname,"w")
# wav params
nchannels = 1
sampwidth = 2
framerate = int(frate)
nframes=datasize
comptype= "NONE"
compname= "not compressed"
wav_file.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname))
#write on file
for s in sine_list:
wav_file.writeframes(struct.pack('h', int(s*amp/2)))
wav_file.close()
frate = 44100.00 #that's the framerate
freq=987.0 #that's the frequency, in hertz
seconds = 3 #seconds of file
data_length = frate*seconds #number of frames
fname = "WaveTest2.wav" #name of file
make_sine(freq, data_length, fname)
这个代码可能不是最快的……不过如果你不追求速度,它完全可以正常工作!