condosz
condosz

Reputation: 553

How to play music in the same folder as my program (Python)

My teacher told us to program a pokemon battle as homework. I've already worked out most of the program, but I want to add the battle music to it.

I've seen a lot of options, but all of these need me to know the directory of the music file, which I don't, because I'll be sending my files to my teacher for correction.

Is there a way to make python play a music file within the same folder as the main program?

(Tried my best to ask it right, english is not my mother tongue)

EDIT: Most solutions need me to install packages, which I'm trying to avoid. One solution that doesn't need me to do that is:

import os
open('battle.mp3')
os.startfile('battle.mp3')

But it opens the file not within python but on my default player. Isn't there a way to make python reproduce it? Maybe a module? I've seen that some packages let you time the music. Can I do that too?

EDIT2: When I use the function open(), how do I then play the file?

Upvotes: 2

Views: 2426

Answers (1)

Sergey Gornostaev
Sergey Gornostaev

Reputation: 7787

Filenames without path are relative to the script directory. So your can simply use something like some_audio_play_function('audiofile.wav').

If you need the absolute path to the audio file: The special global variables __file__ is set to the name of the script file. You can use it to get absolute path to the script directory

import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

and absolute path to the audio file in that directory

audio_file_path = os.path.join(BASE_DIR, 'audiofile.wav')

Upvotes: 1

Related Questions