-3

我想制作一个在后台播放音频文件的脚本,所以我在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 文件)为我运行它,所以我尝试从我的 Python 文件中的os 模块startfile()调用该函数,如下所示:

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()
4

1 回答 1

0

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

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

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

pip3 install python-vlc

并尝试这个简单的方法:

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

(取自在 python 上播放 mp3 歌曲

于 2021-09-21T17:29:52.103 回答