I would like to use pygame to send synthesized sine waves to my speakers, with a different frequency for the left and right side speakers. I would like to toggle between the left and right side speakers, using left and right arrows.
For example, configure to play 1760 hz to the left side, and 1685 hz to the right side.
When, and while, the L_ARROW is pressed, play 1760 hz through the left speaker (right speaker silent). And when, and while, the R_ARROW is pressed, play 1685 hz through the right speaker (left speaker silent).
If neither arrow is pressed, play nothing.
I think I’m close, but am encountering the error “Array must be 2-dimensional for stereo mixer” when interpreting the code
"left_sound = pygame.sndarray.make_sound(left_wave)".
Here’s code, in part from an AI code generator:
# Stereo sound control with Pygame
import pygame
import numpy as np
# Initialize Pygame
pygame.init()
# Set up the audio
pygame.mixer.init(frequency=44100, size=-16, channels=2)
# Generate sound waves
def generate_sound(frequency, duration, sample_rate=44100):
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
wave = 0.5 * np.sin(2 * np.pi * frequency * t)
return wave
# Create left and right sound waves
left_wave = generate_sound(1760, 1)
right_wave = generate_sound(1685, 1)
# Convert to 16-bit signed integers
left_wave = np.int16(left_wave * 32767)
right_wave = np.int16(right_wave * 32767)
# Create sound objects
left_sound = pygame.sndarray.make_sound(left_wave)
right_sound = pygame.sndarray.make_sound(right_wave)
# Control loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
right_sound.stop()
left_sound.play() # Play left sound only
elif event.key == pygame.K_RIGHT:
left_sound.stop()
right_sound.play() # Play right sound only
# Quit Pygame
pygame.quit()
2