Python声音(“贝尔”)

时间:2008-08-17 21:33:40

标签: python macos audio terminal

我希望有一个python程序通过发出哔声来完成任务时提醒我。目前,我使用import os然后使用命令行语音程序来说“处理完成”。我更倾向于它是一个简单的“钟声”。

我知道有一个功能可用于 Cocoa 应用程序NSBeep,但我认为这与此无关。

我也试过

print('\a')

但这没效果。

我正在使用Mac,如果您无法通过我的 Cocoa 评论来判断,那么这可能有所帮助。

6 个答案:

答案 0 :(得分:67)

你试过了吗?

import sys
sys.stdout.write('\a')
sys.stdout.flush()

这适用于我在Mac OS 10.5上

实际上,我认为您最初的尝试也可以进行一些修改:

print('\a')

(你只需要字符序列周围的单引号)。

答案 1 :(得分:10)

如果您安装了PyObjC(Python-Objective-C桥接器)或者在OS X 10.5的系统python(随PyObjC一起提供)上运行,那么您可以

from AppKit import NSBeep
NSBeep()

播放系统警报。

答案 2 :(得分:8)

我从pygame模块尝试了混音器,它运行正常。首先安装模块:

$ sudo apt-get install python-pygame

然后在程序中写下:

from pygame import mixer
mixer.init() #you must initialize the mixer
alert=mixer.Sound('bell.wav')
alert.play()

使用pygame,你有很多自定义选项,你可以另外试验。

答案 3 :(得分:5)

我必须在iTerm的活动终端配置文件中关闭“Silence terminal bell”选项才能使print('\a')正常工作。默认情况下,它似乎在终端中正常工作。

您还可以使用Mac模块Carbon.Snd播放系统提示音:

>>> import Carbon.Snd
>>> Carbon.Snd.SysBeep(1)
>>> 

Carbon模块没有任何文档,因此我必须使用help(Carbon.Snd)来查看可用的功能。它似乎是Carbon的直接接口,因此Apple Developer Connection上的文档可能有所帮助。

答案 4 :(得分:2)

以Barry Wark的答案为基础...... 来自AppKit的NSBeep()工作正常,但也会使任务栏中的终端/应用程序图标跳转。 使用NSSound()的一些额外行可以避免这种情况并提供使用其他声音的机会:

from AppKit import NSSound
#prepare sound:
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/System/Library/Sounds/Ping.aiff', True)
#rewind and play whenever you need it:
sound.stop() #rewind
sound.play()

可以通过命令行locate /System/Library/Sounds/*.aiff找到标准声音文件 NSBeep()使用的文件似乎是'/System/Library/Sounds/Funk.aiff'

答案 5 :(得分:-1)

With the 'beep' function from the beepy module you have the sounds mentioned on the screenshot below.

从蜂鸣声模块中,您可以选择声音的类型