鱼C论坛

 找回密码
 立即注册
查看: 1221|回复: 6

遇到了pygame报错,不知道问题在哪

[复制链接]
发表于 2023-3-27 10:42:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
程式思路:
1.将声音输出调到最大
2.有3个录音文件,
一边播放录音文件,一边弹窗询问是否有声音
若在声音播放完成前点击了是/否的选项,就强行停止当前声音播放,
3.开始播放下一个录音文件并弹出新的窗口来问是否有声音

问题描述:
我发现在强行关闭音频播放的时候可能导致如下错误,但是不知道如何设置防止


                               
登录/注册后可看大图


代码部分如下:
from pygame import mixer
import sounddevice as sd
from comtypes import CLSCTX_ALL
from ctypes import cast, POINTER
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
class audio_manual_check():
    def __init__(self,status):
        self.status = status
        if(status == 'step1'):
            basicname = logsavepath+'\\faudio_function_before_all.wav'
            afters3name = logsavepath+'\\faudio_function_after_s3.wav'
            afters4name =  logsavepath+'\\faudio_function_after_s4.wav'
            resultfile = program_results['front audio']
            manual_check_file = faudio_manual_check_file
        elif(status == 'step2'):
            basicname = logsavepath+'\\baudio_function_before_all.wav'
            afters3name = logsavepath+'\\baudio_function_after_s3.wav'
            afters4name = logsavepath+'\\baudio_function_after_s4.wav'
            resultfile = program_results['back audio']
            manual_check_file = baudio_manual_check_file
        self.ans = False
        audio_check = self.set_audio_device()
        if(audio_check == False):
            self.ask_window(title='提示',choosetype = 1,filename='')
        else:
            self.ans = True
        if self.ans == True:
            with open(manual_check_file,'w',encoding='utf-8')as f:
                f.write('yes')
            self.set_speaker_volume()
            if os.path.exists(basicname):
                check = True
                mixer.init()
                mixer.music.load(basicname)
                mixer.music.play()
                self.ask_window(title='Result check',choosetype = 2,filename=basicname)
                if self.ans == False:
                    check = False
            else:
                check = False
            if(check == False):
                with open(resultfile,"w",encoding='utf-8') as f:
                    f.write('fail')
                try:
                    mixer.music.stop()
                    pygame.quit()
                    return
                except:
                    return
            try:
                mixer.music.stop()
            except:
                pass
            if os.path.exists(afters3name):
                check = True
                mixer.music.load(afters3name)
                mixer.music.play()
                self.ask_window(title='Result check',choosetype = 3,filename=afters3name)
                if self.ans == False:
                    check = False
            else:
                check = False
            if(check == False):
                with open(resultfile,"w",encoding='utf-8') as f:
                    f.write('fail')
                try:
                    mixer.music.stop()
                    pygame.quit()
                    return
                except:
                    return
            if(check == True):
                try:
                    mixer.music.stop()
                except:
                    pass
                if os.path.exists(afters4name):
                        check = True
                        mixer.music.load(afters4name)
                        mixer.music.play()
                        self.ask_window(title='Result check',choosetype = 4,filename=afters4name)
                        if self.ans == False:
                            check = False
                else:
                    check = False
                if(check == False):
                    with open(resultfile,"w",encoding='utf-8') as f:
                        f.write('fail')
                try:
                    mixer.music.stop()
                    pygame.quit()
                    return
                except:
                    return
        else:
            with open(resultfile,"w",encoding='utf-8') as f:
                f.write('fail')
            with open(manual_check_file,'w',encoding='utf-8')as f:
                f.write('yes')

    def ask_window(self,title,choosetype,filename):
        self.filename = filename
        self.music_check = False
        self.win = tk.Tk()
        self.count = 30
        w,h = 400,180
        # Define Color
        bgcolora = '#0099CC'
        bgcolorb = '#FFFFCC'
        bgcolorc = '#666699'
        # Add a title      
        self.win.title(title)
        self.win.attributes('-topmost',1)
        self.win.wm_geometry('')
        #self.win.geometry('%sx%s'%(w,h))
        self.win.geometry("+"+str(int(int(self.win.winfo_screenwidth())/2)-int(w/2))+"+"+str(int(int(self.win.winfo_screenheight())/2-int(h/2))))
        # Disable resizing the GUI
        self.win.resizable(0,0)
        self.win.iconbitmap(iconfile)
        self.win.protocol('WM_DELETE_WINDOW',self.callback) # 窗体的通信协议方法
        #background color
        self.win.config(background=bgcolora)#"#f4fffc")
        if(choosetype == 1):
            message1 = "即将测试audio声音文件"
            message2 = "检测到当前无audio输入输出设备"
            message3 = "请接入设备后,点击重新检测或Fail audio function"
        elif(choosetype == 2):
            message1 = "正在检测:Front Audio Function"
            message2 = "正在播放30s的音频,剩余时间 : 30s"
            message3 = "请确认是否有声音输出且声音流畅"
        elif(choosetype == 3):
            message1 = "正在检测:after S3"
            message2 = "正在播放30s的音频,剩余时间 : 30s"
            message3 = "请确认是否有声音输出且声音流畅"
        elif(choosetype == 4):
            message1 = "正在检测:after S4"
            message2 = "正在播放30s的音频,剩余时间 : 30s"
            message3 = "请确认是否有声音输出且声音流畅"
        textlabel = LabelFrame(self.win,bg=bgcolorb,bd=0)
        text1=tk.Label(textlabel,text=message1,bg=bgcolorb,fg='Red',font=('黑体', 16, 'bold'))
        text1.pack(anchor=tk.W,pady=5)
        self.text2=tk.Label(textlabel,text=message2,bg=bgcolorb,fg=bgcolorc,font=('黑体', 14))
        self.text2.pack(anchor=tk.W,pady=5)
        text3=tk.Label(textlabel,text=message3,bg=bgcolorb,fg=bgcolorc,font=('黑体',14))
        text3.pack(anchor=tk.W,pady=5)
        textlabel.pack(padx=10,pady=10,fill=BOTH)
        btnlabel = LabelFrame(self.win,bd=0,background=bgcolora)
        if(choosetype != 1):
            pause = 25
            yesbtn =tk.Button(btnlabel, text="是", relief='raised', width=6, height=1,font=("Times",12,"bold"),fg = bgcolorc,bg = bgcolorb,command=self.yes_part)
            yesbtn.grid(row=0,column=0,padx=pause,sticky=N)
            nobtn =tk.Button(btnlabel, text="否", relief='raised', width=6, height=1,font=("Times",12,"bold"),fg = bgcolorc,bg = bgcolorb,command=self.no_part)
            nobtn.grid(row=0,column=2,padx=pause,sticky=N)
            playbtn =tk.Button(btnlabel, text="重新播放", relief='raised', width=10, height=1,font=("Times",12,"bold"),fg = bgcolorc,bg = bgcolorb,command=self.replay_part)
            playbtn.grid(row=0,column=1,padx=pause,sticky=N)
            btnlabel.pack(padx=10,pady = 10,fill = BOTH)
            self.win.after(1000,self.jian)
        else:
            pause = 60
            yesbtn =tk.Button(btnlabel, text="重新检测", relief='raised', width=10, height=1,font=("Times",12,"bold"),fg = bgcolorc,bg = bgcolorb,command=self.detect_audio)
            yesbtn.grid(row=0,column=0,padx=pause,sticky=N)
            nobtn =tk.Button(btnlabel, text="Audio Fail", relief='raised', width=10, height=1,font=("Times",12,"bold"),fg = bgcolorc,bg = bgcolorb,command=self.no_part)
            nobtn.grid(row=0,column=2,padx=pause,sticky=N)
            btnlabel.pack(padx=10,pady = 10,fill = BOTH)
        #======================
        # Start GUI
        #======================
        self.win.mainloop()

    def callback(self):
        pass
   
    def djs(self):   
        if(self.count > 0):
            self.text2["text"]=("正在播放30s的音频,剩余时间 : %ss"%self.count)
            self.s=self.win.after(1000,self.jian)
        else:
            self.text2["text"]=("音频播放已完成,点击重新播放")
            
    def jian(self):
        try:
            self.count -= 1
        except:
            self.count = 29
        self.djs()

    def detect_audio(self):
        self.win.destroy()
        audio_manual_check(self.status)

    def yes_part(self):
        self.win.destroy()
        self.ans = True
        if(self.music_check == True):
            try:
                mixer.music.stop()
                pygame.quit()
                return
            except:
                return
   
    def no_part(self):
        self.win.destroy()
        self.ans = False
        if(self.music_check == True):
            try:
                mixer.music.stop()
                pygame.quit()
                return
            except:
                return

    def replay_part(self):
        mixer.init()
        mixer.music.load(self.filename)
        mixer.music.play()
        self.music_check = True
        self.count = 30

    def set_audio_device(self):
        alldevice = sd.query_devices()
        minput,moutput,setname = None,None,None
        for a in alldevice:
            if('Realtek(R) Audio' in a['name']):
                if('Microphone' in a['name']):
                    minput = a['index']
                if('麦克风' in a['name']):
                    minput = a['index']
                if('Speakers' in a['name']):
                    moutput = a['index']
                    setname = a['name']
                if('扬声器' in a['name']):
                    moutput = a['index']
                    setname = a['name']
            if(minput != None)and(moutput != None):
                break
        if(minput == None)and(moutput == None):
            for a in alldevice:
                if('High Definition' in a['name']):
                    if('Microphone' in a['name']):
                        minput = a['index']
                    if('麦克风' in a['name']):
                        minput = a['index']
                    if('Speakers' in a['name']):
                        moutput = a['index']
                        setname = a['name']
                    if('扬声器' in a['name']):
                        moutput = a['index']
                        setname = a['name']
                if(minput != None)and(moutput != None):
                    break
        if(minput != None)and(moutput != None):
            try:
                sd.default.device = [minput,moutput]
                for f in (str(sd.query_devices()).split('\n')):
                    if('<'in f):
                        if(moutput in f):
                            print('audio output set successfully')
                            return True
                return True
            except:
                print('First Set audio device fail')
                print('Ready to set second time')
                try:
                    workpath = os.getcwd()
                    os.chdir(workpath+'\\lib')
                    os.system("nircmdc setdefaultsounddevice %s" % setname)
                    os.chdir(workpath)
                except:
                    print('Second Set audio device fail')
                    return False
        else:
            print('No audio device found')
            return False

    def set_speaker_volume(self):
        devices = AudioUtilities.GetSpeakers()
        interface = devices.Activate(
            IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
        volume = cast(interface, POINTER(IAudioEndpointVolume))

        # 判断是否静音,mute为1代表是静音,为0代表不是静音
        mute = volume.GetMute()
        if mute == 1:
            print('Speaker当前是静音状态')
            print('尝试设置Speaker为非静音状态')
            setcheck = volume.SetMute(0,None)
            if(setcheck == 1):
                print('设置Speaker为非静音状态 - 成功')
            else:
                print('设置Speaker为非静音状态 - 失败')
        else:
            print('Speaker当前是非静音状态')

        # 获取音量值,0.0代表最大,-65.25代表最小
        vl = volume.GetMasterVolumeLevel()
        print('当前Speaker音量值为%s' % vl)

        # 获取音量范围,我的电脑经测试是(-65.25, 0.0, 0.03125),第一个应该代表最小值,第二个代表最大值,第三个不知道是干嘛的。也就是音量从大到小是0.0到-65.25这个范围
        try:
            vr = volume.GetVolumeRange()
            print('当前Speaker音量值为%s' % str(vr))
        except:
            vr = (-65.25, 0.0, 0.03125)
            print('使用默认的Speaker音量值为%s' % str(vr))

        # 设置音量, 比如-13.6代表音量是40,0.0代表音量是100
        volume.SetMasterVolumeLevel(vr[1], None)
        print('已设置Speaker音量为100%')


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-3-27 10:44:27 | 显示全部楼层
报错信息呢?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-3-27 11:06:38 | 显示全部楼层
从你的描述和代码中,我可以看出你希望在用户选择“是”或“否”之前强制停止音频播放。

在这种情况下,你可以使用 threading 模块将音频播放移动到单独的线程,然后在需要的时候停止它。

这是一个修改后的代码示例,其中使用了 threading 模块。

首先,将以下导入添加到代码的顶部:
import threading

然后,修改 replay_part 方法,将音频播放移动到单独的线程:
def replay_part(self):
    def play_audio():
        mixer.init()
        mixer.music.load(self.filename)
        mixer.music.play()
        self.music_check = True

    self.count = 30
    self.audio_thread = threading.Thread(target=play_audio)
    self.audio_thread.start()


最后,在 yes_part 和 no_part 方法中,在尝试停止音频播放之前,确保先加入音频线程:
def yes_part(self):
    self.win.destroy()
    self.ans = True
    if self.music_check:
        try:
            self.audio_thread.join()
            mixer.music.stop()
            pygame.quit()
            return
        except:
            return

def no_part(self):
    self.win.destroy()
    self.ans = False
    if self.music_check:
        try:
            self.audio_thread.join()
            mixer.music.stop()
            pygame.quit()
            return
        except:
            return


这样,当用户选择“是”或“否”时,将确保音频播放线程结束,从而避免可能的错误。这是一个简单的修改,希望对你有所帮助!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-3-27 13:59:52 | 显示全部楼层
报错信息是图片没有显示出来,
我找不到放置图片的位置
报错信息如下:
Fatal Python error:pygame_parachute:(pygame parachute) Segmentation Fault
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-3-27 14:00:36 | 显示全部楼层
鸩为茗 发表于 2023-3-27 13:59
报错信息是图片没有显示出来,
我找不到放置图片的位置
报错信息如下:

还有一行:Python runtime state :initialized
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-3-27 14:19:45 | 显示全部楼层
isdkz 发表于 2023-3-27 11:06
从你的描述和代码中,我可以看出你希望在用户选择“是”或“否”之前强制停止音频播放。

在这种情况下, ...

改为线程后仍有同样的报错,报错内容我会贴在新楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-3-27 14:24:29 | 显示全部楼层
改为线程后的报错信息如下:
Fatal Python error: (pygame parachute) Segmentation Fault
Python runtime state: initialized

Thread 0x00001e9c (most recent call first):
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 306 in wait
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 558 in wait
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd.py", line 261 in _on_run
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_daemon_thread.py", line 49 in run
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932 in _bootstrap_inner
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 890 in _bootstrap

Thread 0x00004c18 (most recent call first):
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 306 in wait
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 558 in wait
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd.py", line 215 in _on_run
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_daemon_thread.py", line 49 in run
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932 in _bootstrap_inner
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 890 in _bootstrap

Thread 0x00002518 (most recent call first):
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 302 in wait
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 558 in wait
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_timeout.py", line 43 in _on_run
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_daemon_thread.py", line 49 in run
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932 in _bootstrap_inner
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 890 in _bootstrap

Thread 0x00004e48 (most recent call first):
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 204 in _read_line
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 222 in _on_run
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_daemon_thread.py", line 49 in run
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932 in _bootstrap_inner
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 890 in _bootstrap

Thread 0x00004a18 (most recent call first):
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 306 in wait
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\queue.py", line 179 in get
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 367 in _on_run
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_daemon_thread.py", line 49 in run
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932 in _bootstrap_inner
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\threading.py", line 890 in _bootstrap

Current thread 0x00002ef4 (most recent call first):
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 1212 in Release
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 957 in __del__
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2574
in destroy
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2574
in destroy
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2302
in destroy
  File "d:\files\auto-sample-test-v2\bin\Extras\prepare.py", line 2837 in yes_part
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883
in __call__
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1420
in mainloop
  File "d:\files\auto-sample-test-v2\bin\Extras\prepare.py", line 2807 in ask_window
  File "d:\files\auto-sample-test-v2\bin\Extras\prepare.py", line 2695 in __init__
  File "d:\files\auto-sample-test-v2\bin\Extras\prepare.py", line 3165 in <module>
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 124 in _run_code
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 135 in _run_module_code
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 321 in run_path
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy/..\debugpy\server\cli.py", line 284 in run_file
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy/..\debugpy\server\cli.py", line 430 in main
  File "c:\Users\Iris\.vscode\extensions\ms-python.python-2022.16.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy\__main__.py", line 39 in <module>
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 85 in _run_code
  File "C:\Users\Iris\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 192 in _run_module_as_main
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-24 03:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表