pythonaudioarcade

How do I stop the background music in the arcade library?


I need the music to play until the game is over, at which point I'd like it to stop, but nothing I try seems to work. Below is the shortened version of the code I'm working with. If anything, the sound should stop playing immediately because self.game is set to False in the update right away, but no matter what I try the music keeps playing.

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()```

Solution

  • Simple sound control example:

    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()
    

    Sound turns on/off when clicking:

    Sound example