Skip to content

Instantly share code, notes, and snippets.

@juancarlospaco
Last active June 28, 2021 20:59
Show Gist options
  • Save juancarlospaco/c295f6965ed056dd08da to your computer and use it in GitHub Desktop.
Save juancarlospaco/c295f6965ed056dd08da to your computer and use it in GitHub Desktop.
Cross-platform Sound Playing with Standard Libs only, No Sound file is required, No install is required, Python2 / Python3.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys
from tempfile import gettempdir
from subprocess import call
def beep(waveform=(79, 45, 32, 50, 99, 113, 126, 127)):
"""Cross-platform Sound Playing with StdLib only,No Sound file required."""
wavefile = os.path.join(gettempdir(), "beep.wav")
if not os.path.isfile(wavefile) or not os.access(wavefile, os.R_OK):
with open(wavefile, "w+") as wave_file:
for sample in range(0, 1000, 1):
for wav in range(0, 8, 1):
wave_file.write(chr(waveform[wav]))
if sys.platform.startswith("linux"):
return call("chrt -i 0 aplay '{fyle}'".format(fyle=wavefile), shell=1)
if sys.platform.startswith("darwin"):
return call("afplay '{fyle}'".format(fyle=wavefile), shell=True)
if sys.platform.startswith("win"): # FIXME: This is Ugly.
return call("start /low /min '{fyle}'".format(fyle=wavefile), shell=1)
if __name__ in '__main__':
beep()
@juancarlospaco
Copy link
Author

Theres no cross-platform stdlib builtin Sound Playing capability on Python, this script solves that problem,
and also creates arbitrary sounds based on sine waves from an Optional Tuple of Integers argument.
Defaults to a Beep sound.

juan@z:~$ python3 temp.py
Playing WAVE '/tmp/beep.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono
Trying:
    beep()
Expecting:
    0
Playing WAVE '/tmp/beep.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono
ok
1 items passed all tests:
   1 tests in __main__.beep
1 tests in 1 items.
1 passed and 0 failed.
Test passed.

juan@z:~$ python2 temp.py
Playing WAVE '/tmp/beep.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono
Trying:
    beep()
Expecting:
    0
Playing WAVE '/tmp/beep.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono
ok
1 items passed all tests:
   1 tests in __main__.beep
1 tests in 1 items.
1 passed and 0 failed.
Test passed.

juan@z:~/code$
  • windowsound is MS Windows-only, pygame need third party modules, this one depends on nothing.
  • Valid values on the Tuple Argument are positive Integers >0 and <128.
  • Theres no point to use something like random.randint() because you dont feel the difference.

Copy link

ghost commented May 6, 2017

Yay!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment