Created
March 2, 2021 12:27
-
-
Save mhamilt/862af4e0334d7b1e33893bc56b9d055c to your computer and use it in GitHub Desktop.
Wave file with only Python standard libraries
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
import struct | |
import wave | |
import os | |
from math import sin, tau | |
sample_rate = 44100.0 | |
duration = 2.0 | |
frequency = 440.0 | |
num_samples = int(sample_rate * duration) | |
bit_depth = 16 | |
max_amplitude = 2 ** (bit_depth - 1) | |
gain = 0.2 | |
phase_delta = tau * frequency / sample_rate | |
filename = 'A440-Hz.wav' | |
wave_file = wave.open(filename, 'w') | |
wave_file.setnchannels(1) # mono | |
wave_file.setsampwidth(bit_depth // 8) # 16-bit depth i.e. 2 bytes | |
wave_file.setframerate(sample_rate) | |
for i in range(num_samples): | |
value = sin(i * phase_delta) * gain * max_amplitude | |
byte_data = struct.pack('<h', int(value)) | |
wave_file.writeframesraw(byte_data) | |
wave_file.close() | |
print("File saved to:\n", os.getcwd() + '/' + filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment