No sound is played in pygame

后端 未结 1 1799
挽巷
挽巷 2021-01-29 07:19

I made a program to play music at random using python-pygame. When I tried to run, the audio did not play ... By the way, I think that the problem is pygame because the volume i

相关标签:
1条回答
  • 2021-01-29 07:50

    Seems you want to play only one file randomly chosen. You want something like this:

    import pygame
    import sys
    import glob
    from random import choice
    
    allmusic = glob.glob("*.mp3") 
    played = choice(allmusic) #select randomly one element from the list
    
    print(played) #print the name of the chosen file
    pygame.mixer.init()
    
    pygame.mixer.music.load(played)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        pass
    

    the last while loop checks if the music is played, and do nothing until the music ends. It's purpose is to keep the program alive, otherwise it ends immediately and the music stream is terminated.

    Notice that you do not have control on the music, it will play until the end with no way to stop it before. To have some control of this kind, you need a more complex script handling events (from keyboard or a custom GUI interface you create, but this is going too far from your question I think).

    0 讨论(0)
提交回复
热议问题