简体   繁体   English

如何在不打开任何媒体播放器的情况下播放声音文件?

[英]How do you play a sound file without opening any media players?

I'm writing a simple script that I would like to have notify me of an event with a sound file on my computer.我正在编写一个简单的脚本,我想通过我的计算机上的声音文件通知我一个事件。

While I can play a sound file by doing something like:虽然我可以通过执行以下操作来播放声音文件:

import webbrowser
webbrowser.open("C:\Users\User\Desktop\Test\Test.mp3")

That will open up VLC or whatever media player I have, which could alt-tab me / interfere with whatever I was doing.这将打开 VLC 或我拥有的任何媒体播放器,这可能会 alt-tab 我/干扰我正在做的任何事情。

Is there a way to play the sound file without anything popping up?有没有办法播放声音文件而不弹出任何东西? A perfect example of what I am looking to do would be using something like making a beep sound using winsound as such:我想要做的一个完美的例子是使用诸如使用 winsound 发出哔声之类的东西:

import winsound
Freq = 600 # Set Frequency To 600 Hertz
Dur = 800 # Set Duration To 800 ms == 0.8 second(s)
winsound.Beep(Freq,Dur)

Which makes a quick beeping sound without opening any new windows.无需打开任何新的 windows 即可快速发出哔哔声。

This does the trick. 这可以解决问题。 Firstly, install pyglet: 首先,安装pyglet:

pip install pyglet 

Now download and install AVbin from here Do check where AVbin is installed as now you have to go to the installation directory and copy the avbin.dll to the directory where you saved your code. 现在, 从此处下载并安装AVbin 。请检查AVbin的安装位置,因为现在您必须转到安装目录,并将avbin.dll复制到保存代码的目录中。

Finally,run this code: 最后,运行以下代码:

import pyglet
pyglet.lib.load_library('avbin')
pyglet.have_avbin=True
song = pyglet.media.load('filename.mp3')#your file name
song.play()
pyglet.app.run()

Make sure your music file is in the same directory as your code .py file. 确保您的音乐文件与代码.py文件位于同一目录中。 Did this from my experience and it worked. 根据我的经验,这样做是否奏效。

Solved by @eryksun in the comments with the solution of: @eryksun在评论中使用以下解决方案解决了:

winsound.PlaySound(wav_path, winsound.SND_FILENAME | winsound.SND_ASYNC)

This was the best solution for I've seen for what I was looking for. 这是我所寻找的最佳解决方案。 It uses default libraries, only takes up a single straight-forward line, and does what I need it to. 它使用默认库,仅占用一条直截了当的直线,并且可以满足我的需要。

You should use pygame to solve it您应该使用 pygame 来解决它

def music(music):
    pygame.mixer.init()
    pygame.mixer.music.load(music)
    pygame.mixer.music.play()

it will play sound without opening vlc media player它会在不打开 vlc 媒体播放器的情况下播放声音

search google for more otherwise this will be enough to know搜索谷歌更多否则这将足以知道

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM