0

So here is what I am trying to do.

I have a small program, which makes use of the pygame music player to play an mp3. I have this mp3 in the same directory as my python based exe, so I can run it.

The problem is I have the path to the mp3 specified as a 'SOUND_FILE =' string as shown below:

pygame.init()
SOUND_FILE = r'C:\Users\Michael\Desktop\herprogram\classical.mp3'

pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.mixer.init()

pygame.mixer.music.load(SOUND_FILE)
pygame.mixer.music.play(0)

This means when I run an installation wizard on a different machine, the path to the mp3 will be wrong. It will have some other path/username.

The first part of the path I need to be dynamic, so I can concatenate it to the other half of the path I will specify in the installation wizard using an f string.

I have had a look at the python os module, but can't quite get my head around how to implement this.

Any help much appreciated.

Thanks, Michael

double-beep
  • 5,031
  • 17
  • 33
  • 41
Hydra17
  • 103
  • 7

2 Answers2

1

if the mp3 file it's supposed to be on the Desktop of the user's machine you can go:

from pathlib import Path

SOUND_FILE = f'{Path.home()}\Desktop\herprogram\classical.mp3'
1

You can use os.getlogin() to get the username for the user executing the file.

Or else if you want to get the location of the directory where the file is being executed, you can use os.path.dirname(os.path.abspath(__file__)).

Here's the documentation for os.path in case you want to look into it more.

OneCoolBoi
  • 86
  • 5