Playsound setup with dictionary throws error

Tags: , , ,



The following code is supposed to find all mp3 file paths in a folder (called MP3) and store them in a dictionary for their corresponding keys.

NotePaths = {
"C" : "",
"D" : "",
"E" : "",
"F" : "",
"G" : "",
"A" : "",
"H" : ""
}

def file_startswith_key(file):
    ##Checking if file starts with wanted key
    for key in NotePaths:
        if file.startswith(key):
            return key, True
    return None, False

for root, dirs, files in os.walk("/MP3"):
    for file in files:
        key, bool_value = file_startswith_key(file)
        if file.endswith(".mp3") and bool_value:
            NotePaths[key].append(Str("(os.path.join(root, file))"))

Then, one pair from the dictionary is randomly selected and passed to playsound.

currentKey, currentPath = random.choice(list(NotePaths.items()))
playsound(currentPath)

However, executing my code returns the following error (originally this was an error like this, but the comments of the linked question suggested a method to get a more specific error message which I applied):

Traceback (most recent call last):
  File "C:Users...Musical Quiz.py", line 67, in <module>
    playsound(currentPath)
  File "C:Users...AppDataLocalProgramsPythonPython38libsite-packagesplaysound.py", line 35, in _playsoundWin
    winCommand('open "' + sound + '" alias', alias)
  File "C:Users...AppDataLocalProgramsPythonPython38libsite-packagesplaysound.py", line 31, in winCommand
    raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException: 
    Error 292 for command:
        open "" alias playsound_0.8907395801041198
    Der Befehl erfordert einen Alias-, Datei-, Treiber- oder Gertenamen.

##Attempted translation: the command requires an alias, file name, driver name or (I don't know what the last thing is)     

 

Answer

The path of file and the usage .append() function to the dict is causing the issue (.append can be used for list). Please find the solution below, which will print the correct path. You can use your playsound function accordingly. Cheers!

import os,random


NotePaths = {
"C" : "",
"D" : "",
"E" : "",
"F" : "",
"G" : "",
"A" : "",
"H" : ""
}

def file_startswith_key(file):
    ##Checking if file starts with wanted key
    for key in NotePaths:
        if file.startswith(key):
            return key, True
    return None, False

for root, dirs, files in os.walk("MP3"):
    for file in files:
        key, bool_value = file_startswith_key(file)
        if file.endswith(".mp3") and bool_value:
           NotePaths[key]=(os.path.join(root, file))
          

currentKey, currentPath = random.choice(list(NotePaths.items()))

def playsound(currentPath):
    print(currentPath)

playsound(currentPath)

Output:

MP3/A4.mp3
MP3/D4.mp3


Source: stackoverflow