程序员数学 中有一段播放音频的代码执行出错:
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()
>>>ValueError: Array must be 2-dimensional for stereo mixer
换成如下代码:
import pygame
import numpy as np
pygame.mixer.init(frequency=44100, size=-16, channels=1)
size = 44100
buffer = np.random.randint(-10000, 10000, 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))
或者
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))