如何让 pygames 播放文件夹中的音频?

问题描述

你好,我是编程新手,我想做一个歌曲播放器。

import os
from pygame import mixer
Path = input("please provide path to folder: ")
os.chdir(Path)
mixer.init()
mixer.music.load.(Path)

这是我目前的代码

解决方法

这里我指定了包含所有歌曲的文件夹,您只需要输入特定的歌曲名称即可。(在给出路径时始终使用“\”)

import pygame
pygame.mixer.init()
song=str(input('Song Name: ')) #ask for song name
path='C:\\folder_name\\'+song 

pygame.mixer.music.load(path)
pygame.mixer.music.play(loops=3) #how many times to repeat the song
,

您需要确保程序没有退出。所以添加一个 while 循环。希望这个答案对您有所帮助。

from pygame import mixer
Path = input("please provide path to folder: ")
mixer.init()
mixer.music.load(Path)
# Setting the volume 
mixer.music.set_volume(0.7) 

# Start playing the song 
mixer.music.play() 
# infinite loop 
while True: 
  
    print("Press 'p' to pause,'r' to resume") 
    print("Press 'e' to exit the program") 
    query = input("  ") 
  
    if query == 'p': 
        # Pausing the music 
        mixer.music.pause()      
    elif query == 'r': 

        # Resuming the music 
        mixer.music.unpause() 
    elif query == 'e': 

        # Stop the mixer 
        mixer.music.stop() 
        break