Raspberry pi:从 python 代码生成并播放音调(使用 sox)

Raspberry pi: generate and play tone from python code (with sox)

我正在使用 Raspberry、TKinter 和 sox 构建一个简单的 GUI,使用 python 3。 每次按下 GUI 中的按钮时,我都想播放动态生成的音调。这是代码:

from Tkinter import Tk, Label, Button
import os

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("Random Tone Generator")

        self.label = Label(master, text="Press Generate and enjoy")
        self.label.pack()

        self.generate_button = Button(master, text="Generate", command=self.generate)
        self.generate_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def generate(self):
        os.system('play -n -c1 synth 3 sine 500')

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

这是从终端到这个脚本的调用

sudo python /home/pi/Desktop/soundtest.py

这里是我尝试按下按钮时出现的错误 "Generate"

play FAIL formats: can't open output file `default': select_format error: Operation not permitted

如果我尝试相同的命令 ('play -n -c1 synth 3 sine 500'),它会按预期工作。

我现在搜索了几个小时,我尝试了使用 subprocess 的解决方案,它返回了同样的问题,以及与播放文件相关的解决方案,而我需要在spot因为以后会随机生成

我的问题归结为: 1) 为什么在终端中运行的命令在 python 脚本中不起作用 2) 如何让它工作以便我可以直接从脚本生成音调? 我在某个我找不到的地方读到,在脚本调用期间可能需要指定音频驱动程序。但是我不知道怎么办。

编辑:我安装了 HiFiberry DAC+ pro 声卡,它自动设置为默认声卡(而不是 vc4-hdmi)

**** List of PLAYBACK Hardware Devices ****
card 0: vc4hdmi [vc4-hdmi], device 0: MAI PCM vc4-hdmi-hifi-0 []
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: sndrpihifiberry [snd_rpi_hifiberry_dacplus], device 0: HiFiBerry DAC+ Pro HiFi pcm512x-hifi-0 []
  Subdevices: 1/1
  Subdevice #0: subdevice #0

谢谢 蚂蚁

找到解决方案。

我需要指定要使用的声卡,我通过更改行来做到这一点

os.system('play -n -c1 synth 3 sine 500')

进入这个

os.system("AUDIODRIVER=alsa AUDIODEV=hw:1,0 play -n -c1 synth 3 sine 500")

其中AUDIODEV=hw:1,0是我的声卡的编号 aplay -l