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

2 投票
1 回答
1595 浏览
提问于 2025-04-18 09:37

我现在正在尝试写一个小应用程序来处理声音。主要目标是把一个PS3手柄连接到树莓派上,通过模拟摇杆来播放和修改声音。这只是我想做这个的一个简单介绍。

我写了以下代码来生成一个正弦波,并把它写入一个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 个回答

1

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

对比一下

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

请注意,int8 能存储的最大整数只有可怜的 127。

撰写回答