Problem mixer.music.get_pos() after set position by mixer.music.set_pos()

476 views Asked by At

I use the pygame.mixer module for my music player While doing the project, I came across a problem that I realized was from the pygame.mixer module When I set the new position inside the set_pos() function get_pos() function does not output the new position and outputs the initial position

from time import sleep
from pygame import mixer

mixer.init()
mixer.music.load("file.mp3")
mixer.music.play()
mixer.music.set_pos(10.0)
sleep(2)
print(mixer.music.get_pos())

output:

2000 ms

If for my logic this output is correct:

12000 ms
1

There are 1 answers

0
D_00 On
  • According to the docs for set_pos():

This sets the position in the music file where playback will start. The meaning of "pos", a float (or a number that can be converted to a float), depends on the music format.

For MOD files, pos is the integer pattern number in the module. For OGG it is the absolute position, in seconds, from the beginning of the sound. For MP3 files, it is the relative position, in seconds, from the current position. For absolute positioning in an MP3 file, first call rewind().

So, you could use this code:

def set_pos(s): # /!\ seconds
    pygame.mixer.music.rewind() # mp3 files need a rewind first
    freq = pygame.mixer.get_init()[0] # get the music frequency
    pygame.mixer.music.set_pos(int(s*freq))

However, using set_pos() can give you errors like this, for example with .ogg sound files:

pygame.error: set_pos unsupported for this codec

You should then prefer using pygame.mixer.music.play(loops, start) like this:

pygame.mixer.music.play(0, s) # /!\ seconds

From the docs:

The starting position depends on the format of the music played. MP3 and OGG use the position as time in seconds. For MP3 files the start time position selected may not be accurate as things like variable bit rate encoding and ID3 tags can throw off the timing calculations. For MOD music it is the pattern order number. Passing a start position will raise a NotImplementedError if the start position cannot be set.

As a general rule, you should be using .ogg files since over .mp3 since they had been implemented before and they have a move precise positioning ("For MP3 files the start time position selected may not be accurate").

  • get_pos() can give you weird results, as it only shows for how long the music has been playing. So, it does not take into account the fact that you "jump" a full minute if the music started playing 1 second ago. It will output you 1000 (ms). Docs:

This gets the number of milliseconds that the music has been playing for. The returned time only represents how long the music has been playing; it does not take into account any starting position offsets.


Linked: pygame.error: set_pos unsupported for this codec