File: ringtone.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2020-2025 pacman64
   6 #
   7 # Permission is hereby granted, free of charge, to any person obtaining a copy
   8 # of this software and associated documentation files (the “Software”), to deal
   9 # in the Software without restriction, including without limitation the rights
  10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 # copies of the Software, and to permit persons to whom the Software is
  12 # furnished to do so, subject to the following conditions:
  13 #
  14 # The above copyright notice and this permission notice shall be included in
  15 # all copies or substantial portions of the Software.
  16 #
  17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23 # SOFTWARE.
  24 
  25 
  26 info = '''
  27 ringtone [seconds...]
  28 
  29 
  30 Emit a ringtone as a wave-sound, lasting the number of seconds given, or 1
  31 second by default. The audio output format is RIFF WAVE (wav) sampled at
  32 48khz.
  33 '''
  34 
  35 
  36 from math import exp, isinf, isnan, sin, tau
  37 from struct import Struct
  38 from sys import argv, exit, stderr, stdout
  39 from wave import open as open_wav
  40 
  41 
  42 # handle standard help cmd-line options, quitting right away in that case
  43 if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'):
  44     print(info.strip())
  45     exit(0)
  46 
  47 # default duration is 1 second, but a float argument can override it
  48 duration = 1.0
  49 if len(argv) > 1:
  50     try:
  51         duration = float(argv[1])
  52         if duration < 0 or isnan(duration) or isinf(duration):
  53             duration = 0.0
  54         args = args[1:]
  55     except Exception:
  56         pass
  57 
  58 rate = 48000.0
  59 dt = 1.0 / rate
  60 samples = int(duration * rate)
  61 packer = Struct('<h')
  62 
  63 try:
  64     with open_wav(stdout.buffer, 'wb') as w:
  65         w.setparams((1, 2, rate, samples, 'NONE', 'none'))
  66 
  67         k = 2048.0 * tau
  68         for i in range(samples):
  69             t = i * dt
  70             f = sin(k * t) * exp(-50.0 * (t % 0.1))
  71             w.writeframesraw(packer.pack(int(32767.0 * f)))
  72 except BrokenPipeError:
  73     # quit quietly, instead of showing a confusing error message
  74     stderr.close()
  75     exit(0)
  76 except KeyboardInterrupt:
  77     exit(2)