通过pygame.sndarray播放正弦波时出错

时间:2014-06-13 00:02:02

标签: python audio numpy pygame

我正在努力编写一个小应用程序来操纵声音。 主要目标是将PS3控制器连接到Raspberry Pi,并通过模拟棒播放和修改声音。这只是为了我想要做以下事情的预览。

我编写了以下代码来创建一个正弦波并将其写入一个numpy数组。

import math, numpy
import pygame

pygame.init()
#>>> (6, 0)

SAMPLERATE = 44100

def tone(freq=1000,volume=16000,length=1):
    num_steps = length*SAMPLERATE
    s = []
    for n in range(num_steps):
        value = int(math.sin(n * freq * (6.28318/SAMPLERATE) * length)*volume)
        s.append( [value,value] )
    x_arr = numpy.array(s)
    return x_arr

pygame.sndarray.make_sound(tone())

如果我现在要运行它,我会收到以下错误:

Traceback (most recent call last):
  File "", line 19, in <module>
  File "/usr/lib/python3.4/site-packages/pygame/sndarray.py", line 131, in make_sound
    return numpysnd.make_sound (array)
  File "/usr/lib/python3.4/site-packages/pygame/_numpysndarray.py", line 75, in make_sound
    return mixer.Sound (array=array)
ValueError: Unsupported integer size 8

但我真的不明白错误在哪里。

1 个答案:

答案 0 :(得分:0)

pygame.sndarray.make_sound似乎只支持某些整数类型,例如int8

import numpy
import pygame

pygame.init()
#>>> (6, 0)

wave = numpy.array([[1,1], [2,2], [3,3]], dtype="int64") # default
pygame.sndarray.make_sound(wave)
#>>> Traceback (most recent call last):
#>>>   File "", line 8, in <module>
#>>>   File "/usr/lib/python3.4/site-packages/pygame/sndarray.py", line 131, in make_sound
#>>>     return numpysnd.make_sound (array)
#>>>   File "/usr/lib/python3.4/site-packages/pygame/_numpysndarray.py", line 75, in make_sound
#>>>     return mixer.Sound (array=array)
#>>> ValueError: Unsupported integer size 8

VS

wave = numpy.array([[1,1], [2,2], [3,3]], dtype="int8") # default
pygame.sndarray.make_sound(wave)
#>>> <Sound object at 0x7f6adfd395d0>

请注意,int8可以存储的最大整数是一个微不足道的127。