1

我需要播放音乐直到游戏结束,此时我希望它停止,但我尝试的任何方法似乎都不起作用。下面是我正在使用的代码的缩短版本。如果有的话,声音应该立即停止播放,因为self.game在更新中立即设置为 False,但无论我尝试什么,音乐都会继续播放。

import arcade


SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Game"


class MyGame(arcade.Window):
    def __init__(self, width, height, title):
        super().__init__(width, height, title)
        self.game = True
        self.music = arcade.load_sound("soundtrack.wav")

    def setup(self):
        self.music.play()

    def on_draw(self):
        arcade.start_render()
        arcade.set_background_color(arcade.color.WHITE)

    def update(self, delta_time):
        self.game = False
        if not self.game:
            # stop the music
            ???


window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.setup()
arcade.run()```
4

1 回答 1

1

简单的声音控制示例:

import arcade


class Game(arcade.Window):
    def __init__(self):
        super().__init__(400, 300, 'Sound demo')
        self.text = 'stop'
        self.music = arcade.load_sound(':resources:music/funkyrobot.mp3')
        self.media_player = self.music.play()

    def on_draw(self):
        arcade.start_render()
        arcade.draw_text(text=f'Click to {self.text} music', start_x=200, start_y=150, anchor_x='center', font_size=16)

    def on_mouse_press(self, x, y, button, key_modifiers):
        if self.text == 'stop':
            self.text = 'start'
            self.media_player.pause()
        else:
            self.text = 'stop'
            self.media_player.play()

Game()
arcade.run()

单击时声音打开/关闭:

声音示例

于 2021-12-13T20:00:20.583 回答