Search code examples
python-3.xtkinterpygamepyinstallerpy2exe

Convert python file that contains mp3 song into executable


So I'm trying to convert tkinter file into executable using pyinstaller. I've done it with picture, but when I create executable that contains some sort of audio it says "Failed to execute script playmusic" (playmusic is the script name). I've tried changing the script name, using .wav song, replacing the exe from the dist folder to the script directory together with the song but none of this worked. I've also tried with auto-py-to-exe, but it doesn't work. The song is played with pygame, and works without any issue inside VS Code. It doesn't matter if I am using pyinstaller or some other module. I'm using python 3.8.2 on Windows 10.

This is the python script:

import tkinter as tk
from pygame import mixer, time

root = tk.Tk()
root.title("Music Player")
root.geometry("300x100+800+100")

label1=tk.Label(root, text="Start Song: ", fg='green', anchor="w")
label1.grid(row=0, column=0)

file = 'Ignite.mp3'
mixer.init()
mixer.music.load(file)

play = lambda: mixer.music.play()
button1 = tk.Button(root, text = 'Play', command = play)
while mixer.music.get_busy(): time.Clock().tick(10)
button1.grid(row=0, column=2)

pause = lambda: mixer.music.pause()
button2 = tk.Button(root, text="Pause", command = pause)
button2.grid(row=0, column=3)

resume = lambda: mixer.music.unpause()
button3 = tk.Button(root, text="Resume", command = resume)
button3.grid(row=0, column=4)

stop = lambda: mixer.music.stop()
button4 = tk.Button(root, text="Stop", command=stop)
button4.grid(row=0, column=5)

root.mainloop()

It's kind of a music player. The pyinstaller code I run to execute the script is the following:

pyinstaller --add-data "Ignite.mp3;." --onefile -w playmusic.py

It executes without problem, but when I run the executed script, in a pop-up window it says "Failed to execute script playmusic"


Solution

  • The files has to be in the same directory for the script to be executed correctly.

    If in your script you say:

    file = 'Ignite.mp3'
    mixer.music.load(file)
    

    and if the file is not your same directory(as your script). It would throw an error in python script, hence in your exe too.

    Or you could say something like an absolute path:

    file = 'C:\\somefolder\\some_more_folder\\Ignite.mp3'
    mixer.music.load()
    

    But the first method is recommended as to when you make an exe to release it to some people, so you need a setup file, so the absolute path will not work as it is the path on your computer only. But ypu could specify the location of install to program files and still find a way through but first method is recommended.

    So after making sure of that you can make an exe with pyinstaller code:

    pyinstaller -F -w playmusic.py 
    

    Hope it helped, do let me know if any more errors.

    Cheers