Trying to play a sound wave on python using pygame

人盡茶涼 提交于 2021-02-05 07:56:27

问题


I'm following this example from the book 'math for programmers' but it doesn't work for me:

import pygame, pygame.sndarray
    
pygame.mixer.init(frequency=44100, size=-16, channels=1)
    
import numpy as np
    
arr = np.random.randint(-32768, 32767, size=44100)
    
sound = pygame.sndarray.make_sound(arr)
    
sound.play()

It returns these errors:

... in make_sound return numpysnd.make_sound(array)"
... in make_sound return mixer.Sound(array=array)
ValueError: Array must be 2-dimensionarl for stereo mixer"

The code seems to work for the author but i've tried many different ways to solve it but have failed, any ideas?


回答1:


See pygame.sndarray.array():

Creates a new array for the sound data and copies the samples. The array will always be in the format returned from pygame.mixer.get_init().

In your case, for some reason, the mixer seems to have created a stereo sound format with 2 channels. You can verify that by

print(pygame.mixer.get_init())

Use numpy.reshape to convert the one-dimensional array to a two-dimensional 44100x1 array. Then use numpy.repeat to convert the 44100x1 array to a 44100x2 array, with the 1st channel copied to the 2nd channel:

import pygame
import numpy as np

pygame.mixer.init(frequency=44100, size=-16, channels=1)

size = 44100
buffer = np.random.randint(-32768, 32767, size)
buffer = np.repeat(buffer.reshape(size, 1), 2, axis = 1)

sound = pygame.sndarray.make_sound(buffer)
sound.play()
pygame.time.wait(int(sound.get_length() * 1000))

Alternatively, you can create a random sound for each channel separately:

import pygame
import numpy as np

pygame.mixer.init(frequency=44100, size=-16, channels=1)

size = 44100
buffer = np.random.randint(-32768, 32767, size*2)
buffer = buffer.reshape(size, 2)

sound = pygame.sndarray.make_sound(buffer)
sound.play()
pygame.time.wait(int(sound.get_length() * 1000))

See also How can I play a sine/square wave using Pygame?



来源:https://stackoverflow.com/questions/64950167/trying-to-play-a-sound-wave-on-python-using-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!