1

I'm using pygame to play sounds at a specific frequency, and it's working fine, until I try to play a square wave using a pre-generated array.

I am using scipy and numpy, and the relevant snippets of my code are below:

pygame.mixer.init(frequency = 44100, size = -16, channels = 1, buffer = 2**12)

def play(sample_wave, ms):
    sound = pygame.sndarray.make_sound(sample_wave)
    sound.play(-1)
    pygame.time.delay(ms)
    sound.stop()

def square_wave(hz, peak, duty_cycle=.5, n_sample=44100):
    t = numpy.linspace(0, 1, 500 * 440/hz, endpoint=False)
    wave = scipy.signal.square(2 * numpy.pi * 5 * numpy.sin(t), duty=duty_cycle)
    wave = numpy.resize(wave, (n_samples,))
    return (peak / 2 * wave.astype(numpy.int16))

play(square_wave(440, 4096), 1000)

However, when I run this code, I get an error about the array generated:

Traceback (most recent call last):
  File "/Users/foo/Desktop/freq.py", line 77, in <module>
    play(square_wv(440, 254),1000)
  File "/Users/bar/Desktop/freq.py", line 9, in play
    sound = pygame.sndarray.make_sound(sample_wave)
  File "/Users/baz/Library/Python/3.6/lib/python/site-packages/pygame/sndarray.py", line 80, in make_sound
    return numpysnd.make_sound (array)
  File "/Users/foobar/Library/Python/3.6/lib/python/site-packages/pygame/_numpysndarray.py", line 75, in make_sound
    return mixer.Sound (array=array)
ValueError: Array has unsupported item format 'd'

What is the cause of this error? I'd really appreciate it if someone happened to know, because it seems to be undocumented across the web in general.

UPDATE:

https://gist.github.com/ohsqueezy/6540433 seems to have another way of generating a square wave. Could anyone explain why this code happens to work and the example above doesn't?

Jon Persan
  • 11
  • 3
  • Maybe [this pygame example](https://www.pygame.org/docs/ref/sndarray.html#comment_pygame_sndarray_make_sound) could help you figure out the correct array formats (I don't have pygame)? – handle Apr 08 '18 at 20:45

0 Answers0