如何阻止 Simpleaudio 同时播放一个文件两次?

How do I stop Simpleaudio from playing a file twice simulaneously?

我在基于文本的冒险游戏中使用 simpleaudio。我正在使用 Python 3. 在我的主循环中,我想实现这个:播放一个简短的音频片段,一旦结束,再次开始播放相同的音频片段。我的问题是,我不知道如何让 Simpleaudio 做到这一点。

我已阅读所有 API 文档,但无济于事。我已经尝试了很多关于循环的不同方法,其中 none 有效。

import simpleaudio as sa

def audio(audiofile):
    filename = "/Users/*********/Desktop/Programming/Python Files/Adventure Game/Audio Files/" + audiofile
    wave_obj = sa.WaveObject.from_wave_file(filename)
    play_obj = wave_obj.play()

A = True
while True:
audio("openingtune.wav")
clear_screen()
firstinput = input("> ")
user_input1(firstinput)

# I didn't include the other functions because they're not relevant to this. 

注意:"while true" 循环每隔一段时间就会刷新一次(在获取输入并给出输出之后)。我不知道该怎么做:歌曲播放完一次后,应该从同一点重新开始。

您当前的方法不起作用,因为您在主线程上播放音频。它一开始就开始按预期播放音频,但在 audio 之后有一系列操作,即所有用户输入。与此同时,audio 可能会停止播放,直到下一次循环才会执行。

解决方案:在单独的线程上启动音频。

代码:

import simpleaudio as sa
from threading import Thread

def audio(audiofile):
    filename = "/Users/*********/Desktop/Programming/Python Files/Adventure Game/Audio Files/" + audiofile
    wave_obj = sa.WaveObject.from_wave_file(filename)
    while(True):
        play_obj = wave_obj.play()

# Let's play the music on a separate thread
audio_thread = Thread(target=audio, args=("openingtune.wav",))
audio_thread.start()

# And now the main game loop
A = True
while True:
    clear_screen()
    firstinput = input("> ")
    user_input1(firstinput)

您可能想要引入一些控件来停止播放音频。

与建议相反,simpleaudio 不在主线程上播放音频。根据文档..

The module implements an asynchronous interface, meaning that program execution continues immediately after audio playback is started and a background thread takes care of the rest. This makes it easy to incorporate audio playback into GUI-driven applications that need to remain responsive.

while 循环应该简单地检查线程是否已完成,如果已完成则再次播放音频。

import simpleaudio as sa


class AudioPlayer:
    def __init__(self):
        self.play_obj = None

    def play(audiofile):
        filename = "/Users/*********/Desktop/Programming/Python 
                    Files/Adventure Game/Audio Files/" + audiofile
        wave_obj = sa.WaveObject.from_wave_file(filename)
        self.play_obj = wave_obj.play()
    
    def is_done():
        if self.play_obj:
            return not self.play_obj.is_playing()
        return True

player = AudioPlayer()
while True:
    clear_screen()
    if player.is_done():
        player.play("openingtune.wav")
    ...

如果您连续播放同一个文件,您可能需要考虑将文件字符串一劳永逸地传递给构造函数。字符串是不可变的,因此 player.play() 调用中的字符串是在循环的每次迭代中创建并通过副本传递的,如果它始终是相同的字符串,那就太疯狂了。