【问题标题】:The "startfile()" function is not working in Python 3.9.7 [duplicate]“startfile()”函数在 Python 3.9.7 中不起作用 [重复]
【发布时间】:2021-11-15 05:48:36
【问题描述】:

我想制作一个脚本在后台播放音频文件,所以我在 Stack Overflow 上找到了代码以静默运行音频文件:

@echo off
set file=song.mp3
( echo Set Sound = CreateObject("WMPlayer.OCX.7"^)
  echo Sound.URL = "%file%"
  echo Sound.Controls.play
  echo do while Sound.currentmedia.duration = 0
  echo wscript.sleep 100
  echo loop
  echo wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000) >sound.vbs
start /min sound.vbs

当我在文件资源管理器中运行该文件时,它按预期工作。

但是,我想要一个 Python 脚本(.py 文件)为我运行它,所以我尝试从我的 os 模块 调用 startfile() 函数python 文件,如下所示:

import os
from locate import this_dir

path = str(this_dir())

os.startfile(path + "\\run_song.py")

这次代码正常,但没有发出声音,终端也没有错误。

我使用 Visual Studio CodePython 3.9.7

我做错了吗?我认为不会。

编辑1:以下是“run_song.py”的内容:

from os import startfile
from locate import this_dir

path = str(this_dir())

startfile(path + "\\sound.vbs")

编辑2:这里是“sound.vbs”的内容:

Set Sound = CreateObject("WMPlayer.OCX.7")
Sound.URL = "song.mp3"
Sound.Controls.play
do while Sound.currentmedia.duration = 0
wscript.sleep 100
loop
wscript.sleep (int(Sound.currentmedia.duration)+1)*1000

编辑 3:尝试了 VLC 模块并得到了这个错误:

FileNotFoundError: Could not find module 'C:\Users\Dani\Desktop\Code\libvlc.dll' (or one of its dependencies). Try using the full path with constructor syntax.   

这是我的代码:

from locate import this_dir
import vlc

path = str(this_dir())

p = vlc.MediaPlayer("file:///" + path + "song.mp3")
p.play()

【问题讨论】:

  • 向我们展示run_song.py的内容。
  • @John Gordon:当然,编辑问题以显示内容。
  • 从尝试让“run_song.py”独立工作开始
  • 我对这个问题有点困惑。在第一句话中,您说音频文件是“静默”运行的。那你说这个程序运行的时候没有声音。如果你想要声音,你为什么要默默地运行它?
  • run_song.py 缺少右括号。那是错字吗?为什么要运行python程序来运行python程序,运行VBS文件?

标签: python batch-file vbscript


【解决方案1】:

os.startfile 不是您要查找的功能。查看文档:

这就像在 Windows 资源管理器中双击文件,或者将文件名作为参数提供给交互式命令外壳中的启动命令:文件将使用与其扩展名关联的任何应用程序(如果有)打开。

为了播放音乐文件,你可以使用安装 vlc python 库

pip3 install python-vlc

试试这个简单的方法:

import vlc
p = vlc.MediaPlayer("C:/path/to/file/file.mp3")
p.play()

(取自Playing mp3 song on python

【讨论】:

  • 出现此错误:FileNotFoundError: 找不到模块 'C:\Users\Dani\Desktop\Code\libvlc.dll'(或其依赖项之一)。尝试使用带有构造函数语法的完整路径。
  • 使用我的代码 + 错误更新问题
  • 编辑得更准确。路径有时会变得烦人(主要是在 Windows 中)。看看 os.path 和 pathlib。另见stackoverflow.com/questions/2953834/windows-path-in-python
  • 是否需要安装 VLC 媒体播放器才能使用该模块?
猜你喜欢
  • 2019-06-04
  • 2016-06-08
  • 1970-01-01
  • 2014-06-30
  • 2021-11-23
  • 2017-11-23
  • 2014-01-12
  • 1970-01-01
相关资源
最近更新 更多