Pygame音频除非以root用户身份运行,否则将无法正常启动

问题描述 投票:0回答:1

因此,我正在研究一个闹钟项目,该项目将作为Homebridge自动化项目的一部分运行,并且我正在编写Python脚本来执行实际的声音警报。该脚本将由homebridge启动,然后播放所有播放声音和打sn等声音。基本上我现在正在做的就是播放声音。我编写了以下简单的脚本,该脚本使用pygame作为音频播放器,以便将来的状态机可以照顾贪睡按钮等。

import pygame
import time

files = ['s1.mp3']

pygame.mixer.init()
pygame.init()






stepper = 0
#file loading
while stepper < len(files):
    pygame.mixer.music.load(files[stepper])
    print("Playing:",files[stepper])
    stepper += 1
    pygame.mixer.music.play()
#play and pause
    while pygame.mixer.music.get_busy():
        timer = pygame.mixer.music.get_pos()
        time.sleep(1)
        control = input("enter control: ")
        pygame.time.Clock().tick(10)
        if control == "pause":
            pygame.mixer.music.pause()
        elif control == "play" :
            pygame.mixer.music.unpause()
        elif control == "time":
            timer = pygame.mixer.music.get_pos()
            timer = timer/1000
            print (str(timer))
        elif control == "exit":
            print ("True")
            pygame.mixer.music.stop()
            break
        else:
            continue

当我在Windows上运行此程序时,效果很好。我可以播放,暂停,查看时间,最重要的是,可以听到声音。但是,当我将它移到我的树莓派上时,它会死,但是只有当它由普通用户启动时才会出现此错误

Hello from the pygame community. https://www.pygame.org/contribute.html
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5047:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM default
Traceback (most recent call last):
  File "musictest.py", line 6, in <module>
    pygame.mixer.init()
pygame.error: No available audio device

如果我以root用户身份运行,即sudo python ./musicTest.py,我没有问题,声音会播放。我希望不必以超级用户身份运行此脚本,也不必真正需要这样做。也许我在这里遗漏了一些东西,但这实际上是必要的,但是我希望对您有所帮助。

到目前为止,我已经尝试更新所有驱动程序和软件包,以查看是否可以解决问题。一旦意识到它以root身份工作,我就停止尝试,这意味着该软件可以正常工作,只是存在某种权限问题。我可以同时从HDMI和耳机端口播放音频。这不是卷的问题,因为它也可以作为根。

我也尝试过this页面,但这也没有解决。如果有人有任何想法,我可以公开提出所有建议或解释,为什么我必须使用sudo :)谢谢!

P.S。我正在安装今天安装在raspberry pi 2 B +上的raspbain lite的新映像,我正在使用python 3.7.3和pygame 1.9。似乎无法找到确切的数字。

python audio pygame raspberry-pi2
1个回答
0
投票

因此,我做了很多修改,发现该问题仅在我的用户登录到控制台时才发生。我试图通过SSH播放音乐,或者更确切地说,通过ssh启动脚本。事实证明,解决方法是将用户添加到音频组中,使他们即使没有登录也可以使用音频驱动程序。这可以通过命令sudo adduser $USER audio完成。但是,我用用户(cbearda3)替换了$ USER。一旦意识到问题仅在于ssh,我就在另一个stack overflow post上找到了这个问题。这是我的解决方案,尽管我意识到我的用例非常具体,但我认为我会为以后出现此问题的任何人记录下来。

© www.soinside.com 2019 - 2024. All rights reserved.