'The "startfile()" function is not working in Python 3.9.7 [duplicate]

I wanted to build a script playing an audio file in the background, so i found code on Stack Overflow to run an audio file without the window popping up:

@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

When i ran the file in File Explorer, it worked perfectly.

But my main goal is to get a Python script (.py file) to run it for me without having any visuals, so i tried calling the startfile() function from the os module in my python file, like this:

import os
from locate import this_dir

path = str(this_dir())

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

This time, no errors were provided, but the sound couldn't be heard.

I use Visual Studio Code and Python 3.9.7

Here is the code inside "run_song.py":

from os import startfile
from locate import this_dir

path = str(this_dir())

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

Here Are The Insides Of "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

Yes, i tried using the VLC module and it didn't work. This error popped up.

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.   

Here Is The Principal File (run_song.py)'s code.

from locate import this_dir
import vlc

path = str(this_dir())

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


Solution 1:[1]

os.startfile is not the function you are looking for. Take a look at the documentation:

this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

In order to play music files, you can install vlc python library using

pip3 install python-vlc

And try this simple method:

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

(taken from Playing mp3 song on python)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1