Untitled

 avatar
unknown
plain_text
10 months ago
951 B
9
Indexable
import pygame
import numpy as np

# Initialize pygame mixer
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.init()

def square_wave(frequency, duration, volume=0.5, sample_rate=44100):
    """Generate a square wave at given frequency and duration"""
    t = np.linspace(0, duration, int(sample_rate * duration), False)
    wave = 0.5 * np.sign(np.sin(2 * np.pi * frequency * t))
    wave = (volume * wave * (2**15 - 1)).astype(np.int16)
    return wave.tobytes()

def play_note(frequency, duration):
    sound = pygame.mixer.Sound(buffer=square_wave(frequency, duration))
    sound.play()
    pygame.time.delay(int(duration * 1000))

# Example 8-bit melody (Super Mario style vibes)
melody = [
    (659, 0.2), (659, 0.2), (0, 0.2), (659, 0.2), 
    (523, 0.2), (659, 0.2), (784, 0.4),
    (392, 0.4)
]

for freq, dur in melody:
    if freq == 0:
        pygame.time.delay(int(dur * 1000))  # rest
    else:
        play_note(freq, dur)

pygame.quit()
Editor is loading...
Leave a Comment