简体   繁体   English

如何在不使用文件或目录的情况下在 python 中播放任何类型的声音

[英]How to play any kind of sound in python without using file or directory

I am writing a program which I will send to someone as a single .py file.我正在编写一个程序,我将把它作为单个 .py 文件发送给某人。 I want to be able to include sound in this program which the person can hear without requiring extra wav/mp3 files as well.我希望能够在这个程序中包含人们可以听到的声音,而无需额外的 wav/mp3 文件。 Is this possible?这可能吗? I'm open to using external modules, etc, just as long as it can all be included in one file when I send it.我愿意使用外部模块等,只要在我发送时可以将其全部包含在一个文件中即可。

您可以使用库winsound将您的音频作为 .py 文件中的字节字符串包含在内。

winsound is a standard python library included with all installations for playing audio on Windows systems; winsound是一个标准的 Python 库,包含在所有用于在 Windows 系统上播放音频的安装中; therefore, the person to whom you are sending the program will only need to have python installed.因此,您向其发送程序的人只需要安装 python。

From the winsound documentation , you can use sounds from the windows registry without any further file dependencies, eg:winsound文档中,您可以使用 Windows 注册表中的声音,而无需任何其他文件依赖项,例如:

import winsound
# Play Windows exit sound.
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

Details of sounds common to all Windows 32 registries are available here . 此处提供所有 Windows 32 注册表通用的声音详细信息。 As stated in the docs, most systems have many more sound aliases available.正如文档中所述,大多数系统都有更多可用的声音别名。

Alternatively, you could encode your audio file as a byte string and include this in your python module.或者,您可以将音频文件编码为字节字符串并将其包含在您的 python 模块中。 You can then pass this bytes object to winsound.PlaySound to play the audio.然后,您可以将此字节对象传递给winsound.PlaySound以播放音频。

Maybe you can use playsound .也许你可以使用playsound The code is pretty simple:代码非常简单:

from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')

Just use the playsound function and send a path to your file as parameter and it will play the sound.只需使用 playsound 函数并将文件路径作为参数发送,它就会播放声音。

I used this library to make an alarm app for my laptop, and it worked.我使用这个库为我的笔记本电脑制作了一个闹钟应用程序,它奏效了。 Good luck!!!祝你好运!!!

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

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