当我在python中播放WAV时,程序在文件结束时不会停止,使程序无响应

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

因此,我们的任务是编写一个为用户播放歌曲的短节目,然后让他们猜测歌曲的类型,之后程序询问他们是否想要听另一首歌或是否想要退出。我遇到的问题是程序首次播放歌曲时。它首先打印出测验的标题,并询问用户是否想要听一首歌,或者输入“-1”退出测验。但是,如果用户选择播放歌曲,则播放该歌曲,但一旦剪辑结束,则不会继续下一个测验的下一部分(猜测类型)。该程序只是停留在这个“播放”模式,我什么也做不了,进入cntrl + C吧。

我已经无情地搜索了这个问题的答案,我已经写出了更简单的程序,只是为了看看它是否会继续播放这首歌,甚至向我的讲师询问这个问题(他没有给我任何奇怪的答案) 。这是我的代码(playWav2是用于播放wav文件的pyaudio脚本):

import playWav2 as pw
#Here I am providing the list of genres and songs for the program to take info from. 
#I am using "s" for the song list, and "i" for the genre list.
genre_list=['melodic punk','alt rock','drum and bass','house','punk rock']
song_list=["Welcome to Paradise.wav","Worry Rock.wav","Propane Nightmares.wav","Lalula.wav","Life During Wartime.wav"]
i=0
s=0
#Here I am providing the participant with the ability to play a song
decision=input("Guess the genre of the song! (enter any key to play a song. Enter -1 to finish the quiz)")
if decision == '-1':
            exit()
else:
    pw.play(song_list[s])        


#Here I am showing the participant the list of possible genres to choose from.
print("heres a list of my favorite genres!")
print(genre_list) 
#Here the participant guesses the genre     
genre=input("What genre do you think that was?")
#If the genre is correct, it plays the next song, if it is not in genre_list, it stops.    
while genre == genre_list[i]:
    print("Great guess! %s is correct!"%(genre))
    choice=input("Ok, so now that you got that right, ready to try another? (y/n)")
    if choice.lower() == 'y':
        i+=1
        i%=5
        pw.play(song_list[s])
    else:
        break

这是播放Wav2的代码:

""" Play a WAVE file. """

import pyaudio
import wave

chunk = 1024

def play(song):
    wf = wave.open(song, 'rb')
    p = pyaudio.PyAudio()

    # open stream
    stream = p.open(format = p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = wf.getframerate(),
                output = True)

    # read data
    data = wf.readframes(chunk)

    # play stream
    while data != '':
        stream.write(data)
        data = wf.readframes(chunk)
    stream.stop_stream()
    stream.close()
    p.terminate()
python audio wav pyaudio
2个回答
0
投票

错误不在上面的代码中,而是在你的模块playWav2中

当您将pyaudio列为参考时,请查看The example on the pyaudio page,特别是示例如何结束..

或者提供playWav2的代码。


0
投票

是的,上面的代码永远不会离开循环。有点晚了,但是当b''(一个空的字节字符串)返回时尝试退出它。这适合我。 (我不得不改变wfsound)。

sound = wave.open("your.wav")
p = pyaudio.PyAudio()
chunk = 1024
stream = p.open(format =
                p.get_format_from_width(sound.getsampwidth()),
                channels = sound.getnchannels(),
                rate = sound.getframerate(),
                output = True)
data = sound.readframes(chunk)
while True:
    if data != '':
        stream.write(data)
        data = sound.readframes(chunk)

    if data == b'':
        break


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.