FileNotFoundError despite the target file being in the same folder as the code

66 views Asked by At

I am trying to play music in the background of my project whilst it is running. Despite the audio file being in the folder containing my Python code I still receive a FileNotFoundError. More specifically: FileNotFoundError: [WinError 2] The system cannot find the file specified

Below is the code relevant to my problem.

from pydub import AudioSegment
from pydub.playback import play

def play_mp3(file_path):
    sound = AudioSegment.from_mp3(file_path)
    repeated_sound = sound * -1
    play(repeated_sound)

MusicThread = threading.Thread(target=play_mp3,args=("Music.mp3",),daemon=True)

MusicThread.start()

I have tried refreshing, closing vscode, using the file path, and using an alternate file path to the same file.

2

There are 2 answers

0
Mohamed ElKalioby On

It is better to get the absolute path when dealing with files so you don't encounter this issue. You do this simply as follows

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

so that we return you the directory name of your script. so to reach your file

MusicThread = threading.Thread(target=play_mp3,args=(main_path + "/Music.mp3",),daemon=True)
4
J Adams On

You'll need to open the file for reading first with open(file_path). See: https://docs.python.org/3/library/functions.html#open

def play_mp3(file_path):
    sf = open(file_path)
    sound = AudioSegment.from_mp3(sf)
    repeated_sound = sound * -1
    play(repeated_sound)