如何在python中播放暂停音频文件?

时间:2019-08-18 12:47:52

标签: python vlc audio-player

我正在尝试使用Python创建一个媒体播放器,该媒体播放器将一个接一个地播放mp3文件,并允许我随时播放和暂停音乐(类似于Spotify)。

我已经使用了vlc库和pygame音乐功能来播放文件,但是我的问题是当歌曲播放完毕并希望它播放下一个文件时。我已经做到了,但是没有播放和暂停功能。

我的粗略代码:

import pygame
import time

#plays first mp3 file
file = '4c68Z9wLdHc36y3CNjwQKM.ogg'
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file)
pygame.mixer.music.play()

#play and pause funtionnality

while pygame.mixer.music.get_busy():
    timer = pygame.mixer.music.get_pos()
    time.sleep(1)
    control = input()
    pygame.time.Clock().tick(10)
    if control == "pause":
        pygame.mixer.music.pause()
    elif control == "play" :
        pygame.mixer.music.unpause()
    elif control == "time":
        timer = pygame.mixer.music.get_pos()
        timer = timer/1000
        print (str(timer))
    elif int(timer) > 10:
        print ("True")
        pygame.mixer.music.stop() 
        break
    else:
        pass

 #next mp3 file   

file = '3qiyyUfYe7CRYLucrPmulD.ogg' 
pygame.mixer.music.load(file)
pygame.mixer.music.play()

运行此文件时,我希望它会播放第一个文件并允许我播放和暂停,但是当歌曲结束时它停止播放,而下一首则不播放,因为它在等待输入时卡住了。

我希望它播放第一个文件,让我随时暂停和恢复它,然后当歌曲结束时,它会自动播放下一个文件。

谢谢。

要缩小范围,我想知道如何创建一个带有用户输入的while,该输入将始终检查条件,而不仅仅是在while循环开始时。

1 个答案:

答案 0 :(得分:0)

如果使用vlc可以说pygame内置了此功能,我不确定为什么要标记这个问题vlc.py
但是,您所需要做的就是使用双while语句。
第一个控制要播放的文件,第二个执行播放/暂停控制。例如

import pygame
import time

files = ['./vp1.mp3','./vp.mp3']
pygame.init()
pygame.mixer.init()
stepper = 0
#file loading
while stepper < len(files):
    pygame.mixer.music.load(files[stepper])
    print("Playing:",files[stepper])
    stepper += 1
    pygame.mixer.music.play()
#play and pause
    while pygame.mixer.music.get_busy():
        timer = pygame.mixer.music.get_pos()
        time.sleep(1)
        control = input()
        pygame.time.Clock().tick(10)
        if control == "pause":
            pygame.mixer.music.pause()
        elif control == "play" :
            pygame.mixer.music.unpause()
        elif control == "time":
            timer = pygame.mixer.music.get_pos()
            timer = timer/1000
            print (str(timer))
        elif int(timer) > 10:
            print ("True")
            pygame.mixer.music.stop()
            break
        else:
            continue