一 前记
项目需要生成不同频点的正玄波信号,没找到现成的软件,只能自己写一个了。顺便温习一下python。
二 源码解析:
#!/usr/bin/python
import numpy as np
from scipy import signal
import wave
import struct
import sys
num_samples = 48000
sampling_rate = 48000.0
amplitude = 16000
comptype = 'NONE'
compname = 'not compressed'
nchannels = 1
sampwidth = 2
FILE_NAME = ''
def createSine(frequency,frequency1,play_time):
# generate the sine wave
new_wave = [np.sin(2 * np.pi * frequency * x/sampling_rate) + np.sin(2 * np.pi * frequency1 * x/sampling_rate) for x in range(num_samples * play_time)]
writeWave(new_wave)
def createWave(frequency, frequency1, wave_type, play_time):
if wave_type == 'sine':
createSine(frequency,frequency1,play_time)
else:
print('Please type in only waveforms from this list! (sine, saw, triangle, square)')
def writeWave(created_wave):
file = FILE_NAME
nframes = num_samples
wav_file = wave.open(file, 'w')
wav_file.setparams((nchannels, sampwidth, int(sampling_rate), nframes, comptype, compname))
for s in created_wave:
# struct.pack with the parameter 'h' means that we're
# writing the data as binaries, not just the numbers.
# 'h' stands for hexadecimal.
# This allows for music players to read the data.
wav_file.writeframes(struct.pack('h', int(s*amplitude)))
def printSuccessful(wave_type, frequency,frequency1, play_time):
print('File \'' + FILE_NAME + '\' created!\n' +
'Wave Type: ' + wave_type + '\n' +
'Frequency_one: ' + frequency + "hz\n"+
'Frequency_two: ' + frequency1 + "hz\n"+
'Play Time: ' + play_time + ' seconds')
def main(wave_type, frequency, frequency1,play_time, file_name):
frequency_Float = float(frequency)
frequency_Float1 = float(frequency1)
wave_type_Str = str(wave_type)
play_time_Int = int(play_time)
file_name = str(file_name)
global FILE_NAME
if len(file_name) < 4:
print('your specified filename: \'' + file_name + '\' is too short. The file name must end in \'.wav\'.\n Do you want me to change your file name to end in \'.wav\'? (y/n)')
answer = input()
if answer == 'y':
FILE_NAME = file_name + '.wav'
createWave(frequency_Float,frequency_Float1,wave_type_Str, play_time_Int)
printSuccessful(wave_type, frequency, frequency1,play_time)
elif answer == 'n':
print('Please press a key to exit.')
input()
else:
FILE_NAME = file_name
createWave(frequency_Float, frequency_Float1, wave_type_Str, play_time_Int)
printSuccessful(wave_type, frequency, frequency1,play_time)
if __name__ == '__main__':
main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4],sys.argv[5])
运行结果:
➜ wave-generator git:(master) ✗ py tone_wave_generator.py sine 900 1800 10 out26.wav
File 'out26.wav' created!
Wave Type: sine
Frequency_one: 900hz
Frequency_two: 1800hz
Play Time: 10 seconds
三 结果分析
生成的wav文件波形图:
对应的频谱图
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。