简体   繁体   中英

How to stop the music when the s key is pressed?

My program plays music when I press the space bar. How to stop music when the s key is pressed?

import pygame, sys
from pygame.locals import QUIT


def main():
    pygame.init()

    #Intalise
    DISPLAYSURF = pygame.display.set_mode((400, 300))
    pygame.display.set_caption('Drop Shadow!')

    #load sound
    beep_sound = pygame.mixer.Sound('Joy.wav')

    #load music
    pygame.mixer.music.load('Joy.wav')

    # Game Clock
    game_clock = pygame.time.Clock()

    #Game Loop
    running = True
    while running:
        #Update Section

        #Update delta_time
        delta_time = game_clock.tick(60) / 100

        #Handle events
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    #play sound
                    pygame.mixer.Sound.play(beep_sound)
                if event.key == pygame.K_p:
                    #play music
                    pygame.mixer.music.play(-1)
                  
        #Draw Section
        DISPLAYSURF.fill((128, 128, 128))

        pygame.display.flip()


    if __name__ == "__main__":
        main()

You can use the pygame.mixer.music.stop() :

Stops the music playback if it is currently playing. endevent will be triggered, if set. It won't unload the music.

Conditionally call it in your event-loop when pygame.K_s is pressed, like so:

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_SPACE:
        #play sound
        pygame.mixer.Sound.play(beep_sound)
    if event.key == pygame.K_p:
        #play music
        pygame.mixer.music.play(-1)
    if event.key == pygame.K_s:
        #stop music
        pygame.mixer.music.stop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM