2

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?

condosz
  • 474
  • 1
  • 5
  • 10
  • If the music file is in the same directory as your program, you can load it with `open('nameofile.wav')` – Burhan Khalid May 16 '16 at 04:16
  • Please edit some example code into your post. If you have some code that plays the music but needs the full directory, include that version code. I'd be surprised if the code actually needs the directory, but it will be easier for people to help you if you include the code. – Marius May 16 '16 at 04:16
  • [pygame](http://stackoverflow.com/a/20021547) can play .mp3 files – Evan Peters May 16 '16 at 08:59

1 Answers1

1

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')
Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39