Python Sound (“Bell”)

后端 未结 6 1043
无人共我
无人共我 2020-11-29 04:03

I\'d like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use import os and then use a command line spee

相关标签:
6条回答
  • I had to turn off the "Silence terminal bell" option in my active Terminal Profile in iTerm for print('\a') to work. It seemed to work fine by default in Terminal.

    You can also use the Mac module Carbon.Snd to play the system beep:

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

    The Carbon modules don't have any documentation, so I had to use help(Carbon.Snd) to see what functions were available. It seems to be a direct interface onto Carbon, so the docs on Apple Developer Connection probably help.

    0 讨论(0)
  • 2020-11-29 04:19

    Have you tried :

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

    That works for me here on Mac OS 10.5

    Actually, I think your original attempt works also with a little modification:

    print('\a')
    

    (You just need the single quotes around the character sequence).

    0 讨论(0)
  • 2020-11-29 04:26

    I tried the mixer from the pygame module, and it works fine. First install the module:

    $ sudo apt-get install python-pygame
    

    Then in the program, write this:

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

    With pygame you have a lot of customization options, which you may additionally experiment with.

    0 讨论(0)
  • 2020-11-29 04:27

    If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do

    from AppKit import NSBeep
    NSBeep()
    

    to play the system alert.

    0 讨论(0)
  • 2020-11-29 04:28

    Building on Barry Wark's answer... NSBeep() from AppKit works fine, but also makes the terminal/app icon in the taskbar jump. A few extra lines with NSSound() avoids that and gives the opportunity to use another sound:

    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()
    

    Standard sound files can be found via commandline locate /System/Library/Sounds/*.aiff The file used by NSBeep() seems to be '/System/Library/Sounds/Funk.aiff'

    0 讨论(0)
  • 2020-11-29 04:35

    From beepy module you can choose your kind of sound

    0 讨论(0)
提交回复
热议问题