首页 > 解决方案 > How can I play a sound through python regardless of file location?

问题描述

I'm trying to play music through python:

import winsound

winsound.PlaySound("A", winsound.SND_FILENAME)
winsound.PlaySound("C", winsound.SND_FILENAME)
winsound.PlaySound("D", winsound.SND_FILENAME)
winsound.PlaySound("D", winsound.SND_FILENAME)

which works, but only while the python file is in the same folder as the sounds. Can I get it to play the sounds from anywhere? Or how do I properly import the sound from a specific path without the python file being with the sound files?

I tried:

   winsound.PlaySound("C:\Users\User_Name\Desktop\Microbit\A", 
   winsound.SND_FILENAME)     

I haven't done any coding in a while and I can't remember how to import things properly.

标签: pythonaudiopath

解决方案


不熟悉windsound库,但通常需要转义'\'。我想您还需要字符串末尾的文件类型(.mp3 等)尝试:

winsound.PlaySound("C:\\Users\\User_Name\\Desktop\\Microbit\\A.file_type", #.mp3, .wav, etc
winsound.SND_FILENAME) 

推荐阅读