"""Sound effects and music. The sounds are generated as WAV files the first time you run this.""" import math import struct import wave from pathlib import Path import pygame HERE = Path(__file__).parent SAMPLE_RATE = 44100 def write_tone(path, notes, volume=0.4): """Write a mono 16-bit WAV made of (frequency, seconds) notes using only the standard library.""" frames = bytearray() for freq, seconds in notes: count = int(SAMPLE_RATE * seconds) for i in range(count): envelope = min(1.0, i / 400, (count - i) / 400) # avoid clicks sample = math.sin(2 * math.pi * freq * i / SAMPLE_RATE) if freq else 0.0 frames += struct.pack("