我尝试在Raspberry Pi B2中使用pygame创建一些短信号 这是我的代码:
#!/usr/bin/python
import pygame
import time
from array import array
from pygame.locals import *
pygame.mixer.pre_init(44100, -16, 1, 1024)
pygame.init()
class ToneSound(pygame.mixer.Sound):
def __init__(self, frequency, volume):
self.frequency = frequency
pygame.mixer.Sound.__init__(self, self.build_samples())
self.set_volume(volume)
def build_samples(self):
period = int(round(pygame.mixer.get_init()[0] / self.frequency))
samples = array("h", [0] * period)
amplitude = 2 ** (abs(pygame.mixer.get_init()[1]) - 1) - 1
for time in xrange(period):
if time < period / 2:
samples[time] = amplitude
else:
samples[time] = -amplitude
return samples
tone_obj = ToneSound(frequency = 800, volume = .5)
tone_obj.play(-1) #the -1 means to loop the sound
time.sleep(2)
tone_obj.stop()
当我运行它时,我得到:
Traceback (most recent call last):
File "beep.py", line 29, in <module>
tone_obj = ToneSound(frequency = 800, volume = .5)
File "beep.py", line 15, in __init__
self.set_volume(volume)
TypeError: fromfile() takes exactly 2 arguments (1 given)
当我评论set_volume函数时,我得到的下一个错误是:
Traceback (most recent call last):
File "beep.py", line 29, in <module>
tone_obj.play(-1) #the -1 means to loop the sound
TypeError: fromfile() takes exactly 2 arguments (1 given)
可能是什么问题?
我更新了pygame,更新了所有需要的库 - 结果相同。
根据pygame文档,set_volume只接受一个参数
我真的不知道该怎么做......
答案 0 :(得分:1)
在Raspberry Pi网站上发布了类似的问题, 见"Morse-code Project not working..."。
那里的解决方案是:
pygame.mixer.Sound.init(self, self.build_samples())
pygame.mixer.Sound.init(self, buffer=self.build_samples())
添加buffer=
为我工作。