[英]How do you play sounds when the python file is in a different directory as the sound file?
So I'm making a text-based game, and after completion, I want to compile the end product to a .exe format so it's fairly easy to share (I plan on using cx_freeze) Now, I wanted to add some background music for the game, the code below works fine IF AND ONLY IF the python file is on the desktop and so is the "sound.wav" I'm looking for ways to execute the sound.wav in background whether it's on the same or different directory as the python file, thanks所以我正在制作一个基于文本的游戏,完成后,我想将最终产品编译为 .exe 格式,以便共享(我计划使用 cx_freeze)现在,我想添加一些背景音乐游戏,下面的代码工作正常,当且仅当 python 文件在桌面上,“sound.wav”也是如此 我正在寻找在后台执行 sound.wav 的方法,无论它是在相同还是不同的目录作为python文件,谢谢
import winsound
winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
Use os
package to generate absolute path to your music file to make sure it always works fine.使用
os
包生成音乐文件的绝对路径,以确保它始终正常工作。
For exampe, if your project's structure is例如,如果您的项目结构是
root
src
your_python_file.py
assets
sound.wav
So you can generate the absolute path to the sound.wav by因此,您可以通过以下方式生成 sound.wav 的绝对路径
import os
# __file__ means the path of the current python script
root_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
bg_path = os.path.join(root_dir, "assets", "sound.wav")
Lets say you have a sub-folder called foo
and a second sub-folder called subfoo
假设您有一个名为
foo
的子文件夹和一个名为subfoo
的第二个子文件夹
If you want go into foo
sub-folder use foo/sound.wav
if you want to go in the second sub-folder subfoo
use foo/subfoo/sound.wav
.如果你想进入
foo
子文件夹使用foo/sound.wav
如果你想进入第二个子文件夹subfoo
使用foo/subfoo/sound.wav
。
If you want to go up a dictionary you can use ./
.如果你想翻字典,你可以使用
./
。 For example if your sound is located in foo
and you script in subfoo
it could be accessed with ./sound.wav
to go up one by one file use ./
again.例如,如果您的声音位于
foo
并且您在subfoo
编写脚本,则可以使用./sound.wav
访问它以一个一个文件上升,再次使用./
。
Otherwise you can use an 'absolute' file path where you start from C:
or the drive you wish to access.否则,您可以使用从
C:
或您希望访问的驱动器开始的“绝对”文件路径。 For example if your file filename was located in Desktop you could use:例如,如果您的文件文件名位于桌面中,您可以使用:
C:/users/username/Desktop/foo/subfoo/sound.wav
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.