Find the Length of a Song with Pygame
Asked Answered
I

3

12

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.

Internal answered 4/8, 2011 at 5:0 Comment(2)
This is on linux with python2.7 if that helps...Internal
mixer.music.get_pos seems to return the total play time for the mixer - i.e. it doesn't reset with each sound played. How do you use that to show the per track progress?Anceline
J
10

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())
Jot answered 9/7, 2012 at 20:48 Comment(2)
a = pygame.mixer.Sound('path/to/music.mp3') pygame.error: Unable to open file 'path/to/music.mp3'Rumilly
I looked it up elsewhere. a.get_length() only works for .ogg and .wavRumilly
T
3

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
Toshikotoss answered 12/12, 2018 at 23:9 Comment(0)
T
1

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.

Thetic answered 4/8, 2011 at 5:27 Comment(4)
.get_length is only for the pygame Sounds, not the pygame.mixer.musicInternal
Right, sorry I missed that. Checking through the documentation furhter, it looks like the reason that won't work is because it streams Music objects in rather than loading them entirely into memory. Much like some MP3 players won't display the song length until the song is fully loaded, only the song never fully loads because pygame doesn't buffer like that. Any reason you can't use a Sound object instead?Thetic
Just figured I should be using the Music object instead of the sound object... Although, I guess I could load the songs for the sake of getting the length...Internal
pygame.mixer.Sounds().get_length()Decision

© 2022 - 2024 — McMap. All rights reserved.