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

﹥>﹥吖頭↗ 提交于 2019-12-11 04:36:22

问题


I am building a simple GUI with Raspberry, TKinter, and sox, using python 3. I want to play a tone, generated on the fly, every time a button in the GUI is pressed. Here's the code:

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()

Here is the call from terminal to this script

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

And here the error I get if I try to push the button "Generate"

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

If I try the same command ('play -n -c1 synth 3 sine 500') it works as expected.

I searched for few hours now and I tried solutions using subprocess, which give back the same problem, and solutions related to playing files, while I need to generate tones on the spot because in the future they will be randomly generated.

My question boils down to: 1) why the command that works in the terminal does not work within the python script 2) how do I make it work so that I can generate tones directly from the script? I read somewhere I can't find anymore that one might need to specify the audio driver during the call from the script. But I wouldn't know how.

EDIT: I have an HiFiberry DAC+ pro sound card installed, which is automatically set to be the default one (instead of the 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

Thanks Ant


回答1:


Found the solution.

I needed to specify the sound card to use and I did so by changing the line

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

into this

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

where the AUDIODEV=hw:1,0 is the number of my sound card derived from aplay -l



来源:https://stackoverflow.com/questions/48769993/raspberry-pi-generate-and-play-tone-from-python-code-with-sox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!