Last active
September 17, 2021 21:05
-
-
Save davcri/35074eda17caf24e0d8269edba58192c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/questions/33879523/python-how-can-i-generate-a-wav-file-with-beeps | |
import math | |
import wave | |
import struct | |
audio = [] | |
sample_rate = 44100.0 | |
def append_silence(duration_milliseconds=500): | |
num_samples = duration_milliseconds * (sample_rate / 1000.0) | |
for x in range(int(num_samples)): | |
audio.append(0.0) | |
return | |
def append_sinewave( | |
freq=440.0, | |
duration_milliseconds=2000, | |
volume=1.0): | |
global audio # using global variables isn't cool. | |
num_samples = duration_milliseconds * (sample_rate / 1000.0) | |
for x in range(int(num_samples)): | |
audio.append(volume * math.sin(2 * math.pi * freq * ( x / sample_rate ))) | |
return | |
def save_wav(file_name): | |
wav_file=wave.open(file_name,"w") | |
nchannels = 1 | |
sampwidth = 2 | |
nframes = len(audio) | |
comptype = "NONE" | |
compname = "not compressed" | |
wav_file.setparams((nchannels, sampwidth, sample_rate, nframes, comptype, compname)) | |
# WAV files here are using short, 16 bit, signed integers for the | |
# sample size. So we multiply the floating point data we have by 32767, the | |
# maximum value for a short integer. NOTE: It is theortically possible to | |
# use the floating point -1.0 to 1.0 data directly in a WAV file but not | |
# obvious how to do that using the wave module in python. | |
for sample in audio: | |
wav_file.writeframes(struct.pack('h', int( sample * 32767.0 ))) | |
wav_file.close() | |
return | |
append_sinewave(freq=20, volume=0.1) | |
# append_silence() | |
# append_sinewave(volume=0.5) | |
save_wav("sine-wave-20hz.wav") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment