简体   繁体   English

使用Python3播放声音文件或声音?

[英]Play a sound file or sound with Python3?

I am learning python. 我正在学习python。 I thought of a fun and do-able(for me as a noob) exercise to test myself with. 我想到了一个有趣且可行的练习(对我而言是菜鸟)来测试自己。

I want to write a script that asks the user for a string.. and then it translates the string into morse code and plays it. 我想编写一个脚本,要求用户输入字符串..然后将字符串转换为莫尔斯电码并播放。 I just dont know how to access/play a sound file in Python... Doesnt really matter what type.. .wav .mp3 or whatever, just whatever works best with Python. 我只是不知道如何在Python中访问/播放声音文件...哪种类型..wav .mp3或其他类型都没有关系,无论哪种类型最适合Python。 It obviously will just be a short beep that will be played for a certain(very short) time length. 很明显,这只是一声短促的哔哔声,将持续一定时间(非常短)。 I saw that people suggest using pygame.. is that the only option? 我看到有人建议使用pygame ..那是唯一的选择吗? For educational purposes I'd like to know how to do this with the standard library(if possible). 出于教育目的,我想知道如何使用标准库(如果可能)执行此操作。 If not a module is fine. 如果不是,一个模块就可以了。

Or better yet, is there a way to create a beep sound with only python code? 还是更好,有没有办法只用python代码创建提示音? In other words no sound file needed at all. 换句话说,根本不需要声音文件。 A function that says "make a sound at x frequency for x time"? 一个函数说“以x频率在x时间内发出声音”?

You could try the winsound library (built in). 您可以尝试使用winsound库(内置)。

By using winsound.PlaySound(filename,winsound.SND_FILENAME) you are able to play WAV audio files. 通过使用winsound.PlaySound(filename,winsound.SND_FILENAME)您可以播放WAV音频文件。

By using winsound.Beep(frequency(in Hz),duration(in miliseconds)) you should be able to produce a beeping sound. 通过使用winsound.Beep(frequency(in Hz),duration(in miliseconds))您应该能够发出蜂鸣声。

There is a slight chance the Beep() function won't work, as is in my case, and i am currently looking into it. Beep()函数极有可能无法正常工作,就我而言,我目前正在研究它。

Take a look at the docs here: https://docs.python.org/3.7/library/winsound.html 在这里看看文档: https : //docs.python.org/3.7/library/winsound.html

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

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