Trying To Play A Sound Wave On Python Using Pygame
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, channel
Solution 1:
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))
Post a Comment for "Trying To Play A Sound Wave On Python Using Pygame"