Home > Blockchain >  Cannot set volume accurately
Cannot set volume accurately

Time:06-05

So today, while I was trying to create a music player using Tkinter with pygame, I noticed something weird. When I tried changing the volume of my player, it was not setting it up accurately. So what the problem is, when I tried to set the volume to 0.9, it ended up putting it to 0.8984375. I have no idea how these two numbers are related. And when I tried to set it to 0.8, it set the volume to 0.796875. But it worked when I put it to 0.5, which means it only works for 0.5 accurately. I have tried every possible way to overcome this, but nothing helped.

So anyone got any idea what is wrong with my pygame? The part of the code which I use to set up the volume is given below:

Note: I have already initiated pygame mixer. Here, the parameter self refers to my player's main class and event is used for my keybinds.

def decVol(self,event):
            d = mixer.music.get_volume()
            print(d) # d is 1.0 now!
            mixer.music.set_volume(0.9)
            print(mixer.music.get_volume()) # Prints as 0.8984375 <--- -_-

I am not providing the rest of the codes since it is useless to reproduce this situation and is working fine (Just some labels and stuff). This is the only part that handles volume. And as far as I know, I think it's something on my computer's end. Well, I'm on windows 10 x64, btw. If you know something about this, please suggest some better ways to do this.

CodePudding user response:

The precision is lost due to the internal representation of volume in pygame.

From pygame source code,

    Mix_VolumeChunk(chunk, (int)(volume * 128));

the volume is multiplied by 128 and cast to a C int. Then, it goes through the reverse process when you retrieve the volume.

    return PyFloat_FromDouble(volume / 128.0);

int(128 * 0.9) / 128 gives you exactly 0.8984375. I don' think there's much you can do about it in Python.

  • Related