Untitled
unknown
plain_text
a year ago
1.9 kB
8
Indexable
import pygame
import time
# Initialize pygame mixer
pygame.mixer.init()
# Define the piano keys and their corresponding sound files (you will need sound files for each key)
key_sounds = {
'C': 'sounds/c.wav',
'D': 'sounds/d.wav',
'E': 'sounds/e.wav',
'F': 'sounds/f.wav',
'G': 'sounds/g.wav',
'A': 'sounds/a.wav',
'B': 'sounds/b.wav',
'C2': 'sounds/c2.wav'
}
# Initialize pygame window
pygame.init()
screen = pygame.display.set_mode((800, 400))
pygame.display.set_caption("Simple Piano App")
# Draw the keys on the screen
def draw_keys():
for i, key in enumerate(key_sounds):
color = (255, 255, 255) if '2' not in key else (0, 0, 0)
pygame.draw.rect(screen, color, (i * 100, 0, 100, 400))
# Play the sound when a key is pressed
def play_sound(key):
if key in key_sounds:
pygame.mixer.music.load(key_sounds[key])
pygame.mixer.music.play()
# Main loop to check for user input
running = True
while running:
screen.fill((0, 0, 0)) # Fill the screen with black
draw_keys()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
play_sound('C')
elif event.key == pygame.K_d:
play_sound('D')
elif event.key == pygame.K_e:
play_sound('E')
elif event.key == pygame.K_f:
play_sound('F')
elif event.key == pygame.K_g:
play_sound('G')
elif event.key == pygame.K_a:
play_sound('A')
elif event.key == pygame.K_b:
play_sound('B')
elif event.key == pygame.K_h: # 'h' for C2
play_sound('C2')
pygame.display.flip()
time.sleep(0.1)
pygame.quit()
Editor is loading...
Leave a Comment