Pygame - ValueError: Array must be 2-dimensional for stereo mixer

Hi this is my simple metronome app :

import numpy as np
import sys
import time
import pygame
from pygame import mixer

def generate_beep(freq, duration, samplerate=44100):
  t = np.linspace(0, duration, int(samplerate * duration))
  audio = np.sin(2 * np.pi * freq * t)
  return audio.astype(np.int16)

if __name__ == "__main__":

  if len(sys.argv) != 3 or sys.argv[1] != "-t":
    print("Usage: python -t <beats_per_minute>")

  bpm = int(sys.argv[2])
  spb = 60 / bpm # seconds per beat


  while True:
    beep = generate_beep(440, 0.25, 44100)
    # Fix reshape error
    beep = beep.reshape(-1)  
    sound = pygame.sndarray.make_sound(beep)

    time.sleep(spb - 0.25)

I have this bogue, don’t know how to repair it :

pygame 2.5.2 (SDL 2.28.3, Python 3.12.1)
Hello from the pygame community.
Traceback (most recent call last):
  File "\OPENMETRONOME\", line 28, in <module>
    sound = pygame.sndarray.make_sound(beep)
  File "\OPENMETRONOME\venv\Lib\site-packages\pygame\", line 92, in make_sound  
    return mixer.Sound(array=array)
ValueError: Array must be 2-dimensional for stereo mixer

From this answer:
Trying to play a sound wave on python using pygame - Stack Overflow

The mixer is defaulting to stereo, but the data you’re giving it is mono.

You can force the mixer to use mono by calling:

mixer.pre_init(channels=1, allowedchanges=0)



Alternatively, you could make the sound sample stereo by duplicating it:

audio = np.repeat(audio.reshape(audio.shape[0], 1), 2, axis=1)

and omitting the beep = beep.reshape(-1) .

1 Like