小码问答,有问必答!

Python如何播放音乐?

Python

收藏

1个回答

我要回答

  • author
    牛叔叔 2020-08-06 16:32

    使用pip安装pygame。


    简单代码如下:

    def play_music(filepath,vol):
    
        pygame.mixer.init()
        flag = False
        while 1:
            if flag == 0:
                pygame.mixer.music.load(filepath)
                pygame.mixer.music.set_volume(vol)
                pygame.mixer.music.play(start=0.0)
            if pygame.mixer.music.get_busy()==True:
                flag = True
            else:
                if flag:
                    pygame.mixer.music.stop()
                    break;
        print("播放完毕")
        #pygame.mixer.music.stop()


    使用这个播放方法设计两个菜单驱动的小程序测试一下

    from os import environ
    import threading
    import time
    import pygame
    environ['PYGAME_HIDE_SUPPORT_PROMPT']='1'
    def play_music(filepath,vol):
    
        pygame.mixer.init()
        flag = False
        while 1:
            if flag == 0:
                pygame.mixer.music.load(filepath)
                pygame.mixer.music.set_volume(vol)
                pygame.mixer.music.play(start=0.0)
            if pygame.mixer.music.get_busy()==True:
                flag = True
            else:
                if flag:
                    pygame.mixer.music.stop()
                    break;
        print("播放完毕")
        #pygame.mixer.music.stop()
    vol = 0.1
    playing = False
    def play():
        global  playing
        global  vol
        if (playing):
            pass
        else:
            filepath = "D:\\万码学堂音乐\\冬子 - 这一生关于你的风景 (原唱_隔壁老樊).mp3"
            t1 = threading.Thread(target=play_music,args=(filepath,vol))
            t1.start()
            playing = True
            print("开始播放音乐...")
    
    def stop():
        global  playing
        pygame.mixer.music.stop()
        playing = False
    
    def turn_vol(change):
        global  vol
        if change==1:
            vol += 0.1
        elif change==-1:
            vol -= 0.1
        pygame.mixer.music.set_volume(vol)
        print("音量调整为",vol)
    def menu():
        while True:
            print("===菜单====")
            print("1、开始播放音乐")
            print("2、暂停播放音乐")
            print("3、音量变大")
            print("4、音量变小")
            choose = input("输入选择:")
            if choose=='1':
                play()
            elif choose=='2':
                stop()
            elif choose=='3':
                turn_vol(1)
            elif choose=='4':
                turn_vol(-1)
    
    menu()


    windows10,Python3亲测有效。