简体   繁体   中英

Find the Length of a Song with Pygame

I'm building an Radio Automation Program, but I can't figure out how to have a timer countdown the number of seconds left in the song. I'm currently using Pygame and don't really want to load another toolkit just for this. So far I can make a timer count up using this:

import pygame

#setup music
track = "Music/Track02.wav"
pygame.mixer.music.load(track)
pygame.mixer.music.play()
print("Playing Music")
while(pygame.mixer.music.get_busy()):
    print "\r"+str(pygame.mixer.music.get_pos()),

But I have no idea how to get the total length of the song and countdown without having played the song already.

You could also load the song as a normal sound and then check the length while using mixer.music for playing it.

a = pygame.mixer.Sound("test.wav")
print("length",a.get_length())

The mutagen.mp3 can be used to find the length of music.

Firstly: pip install mutagen

-> İmport:

from pygame import *
from mutagen.mp3 import MP3

-> Use:

mixer.music.load('example.mp3')
song = MP3('example.mp3')
songLength = song.info.length

Check the Documentation . According to the site, this function returns the length of a sound object in seconds. So, time remaining is simply (pygame.mixer.music.get_length() - pygame.mixer.music.get_pos())*-1 .

That way, it displays as a negative number like most time remaining counters do in a music player. Note, I don't have pygame on this computer, so I can't test it. So, check it just to make sure.

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