Last active
July 16, 2026 08:07
-
-
Save eliasdorneles/3139dbdf01bb2553c90a8e00db1af0b1 to your computer and use it in GitHub Desktop.
Example creating WAVE file by hand in Python (8-bit)
This file contains hidden or 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 sys | |
| import math | |
| import struct | |
| import array | |
| # Writing a WAVE file, the silly but educational way | |
| duration = 2 # seconds | |
| samplerate = 44100 # how many samples per second | |
| nchannels = 1 # 1 channel, mono audio -- for stereo, we'd use 2 channels | |
| num_of_samples = duration * samplerate | |
| block_align = nchannels * 1 # 1 byte per sample (8-bit) | |
| data_size = num_of_samples * block_align | |
| out = sys.stdout.buffer | |
| # 1st: the RIFF header, which says "hey, i am a wave file!" | |
| out.write(b'RIFF') | |
| out.write(struct.pack('<I', 36 + data_size)) | |
| out.write(b'WAVE') | |
| # 2nd: the format chunk, specifying audio signal parameters | |
| out.write(b'fmt ') | |
| out.write(struct.pack('<I', 16)) # chunk size | |
| out.write(struct.pack('<H', 1)) # PCM | |
| out.write(struct.pack('<H', nchannels)) | |
| out.write(struct.pack('<I', samplerate)) | |
| out.write(struct.pack('<I', block_align * samplerate)) # byte rate | |
| out.write(struct.pack('<H', block_align)) | |
| out.write(struct.pack('<H', 8)) # bit depth: this works the "resolution" of our audio signal | |
| # 3rd: finally, the data chunk | |
| out.write(b'data') | |
| out.write(struct.pack('<I', data_size)) | |
| # --- audio samples --- | |
| volume = 0.5 | |
| samples = array.array('B') # unsigned byte, 8-bit | |
| def scale_sample(value: float) -> int: | |
| # For simplicity, we'll use 8-bit PCM samples, which are stored as | |
| # unsigned bytes (0 to 255) where 128 is silence (the midpoint) | |
| to_scale = (value + 1) / 2 # remap [-1, 1] -> [0, 1] | |
| return int(max(0, min(255, round(to_scale * 255)))) | |
| for frame_idx in range(num_of_samples): | |
| t = frame_idx / samplerate | |
| # here we generate a sine wave signal... | |
| signal = volume * math.sin(2 * math.pi * (220 + 0.01 * frame_idx) * t) | |
| samples.append(scale_sample(signal)) | |
| out.write(samples.tobytes()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment