Настройка воспроизведения звука с ошибкой словаря
Следующий код должен найти все пути к файлам mp3 в папке (называемой MP3) и сохранить их в словаре для соответствующих ключей.
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))"))
Затем случайным образом выбирается одна пара из словаря и передается в playound:
currentKey, currentPath = random.choice(list(NotePaths.items()))
playsound(currentPath)
Однако выполнение моего кода возвращает следующую ошибку (изначально это была ошибка, подобная этой, но в комментариях к связанному вопросу был предложен метод получения более конкретного сообщения об ошибке, которое я применил):
Traceback (most recent call last):
File "C:\Users\...\Musical Quiz.py", line 67, in <module>
playsound(currentPath)
File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.py", line 35, in _playsoundWin
winCommand('open "' + sound + '" alias', alias)
File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\site-packages\playsound.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)
1 ответ
Решение
Путь к файлу и использование функции .append() для dict вызывает проблему (для списка можно использовать .append). Найдите решение ниже, которое напечатает правильный путь. Соответственно, вы можете использовать функцию воспроизведения звука. Ваше здоровье!
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)
Выход:
MP3/A4.mp3
MP3/D4.mp3