Skip to content

Instantly share code, notes, and snippets.

@DevStefIt
Created January 1, 2024 13:06
Show Gist options
  • Save DevStefIt/63e5d8589d1f5cc51ecf554a190b1fa3 to your computer and use it in GitHub Desktop.
Save DevStefIt/63e5d8589d1f5cc51ecf554a190b1fa3 to your computer and use it in GitHub Desktop.
WAV file creator and parser as explained in the related video
import wave
import struct
import math
# Audio parameters
sample_width = 2
sample_rate = 44100
duration = 5
# Define the melody
melody = [
(440, 0.5), # A4
(523.25, 0.5), # C5
(587.33, 0.5), # D5
(659.25, 0.5), # E5
(587.33, 0.5), # D5
(523.25, 0.5), # C5
(440, 0.5), # A4
]
# Create a new WAV file
with wave.open('output.wav', 'wb') as wav_file:
wav_file.setnchannels(1) # Mono audio
wav_file.setsampwidth(sample_width)
wav_file.setframerate(sample_rate)
num_frames = int(sample_rate * duration)
for freq, amp in melody:
# Generate audio samples for each note
num_note_frames = int(sample_rate * amp)
for frame in range(num_note_frames):
t = float(frame) / sample_rate
value = int(amp * 32767.0 * math.sin(2.0 * math.pi * freq * t))
# Pack the sample into the appropriate format
packed_value = struct.pack('<h', value)
# Write the sample to the WAV file
wav_file.writeframesraw(packed_value)
print("WAV file created!")
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment