Advertisement
here2share

# soundwave.py

May 26th, 2019
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. # soundwave.py
  2.  
  3. from struct import pack
  4. from math import sin, pi
  5.  
  6. dir=r"C:/pydemo/test/"
  7. def au_file(name=dir+'test.au', freq=440, dur=1000, vol=0.5):
  8.     """
  9.     creates an AU format sine wave audio file
  10.     of frequency freq (Hz)
  11.     of duration dur (milliseconds)
  12.     and volume vol (max is 1.0)
  13.     """
  14.     fout = open(name, 'wb')
  15.     # header needs size, encoding=2, sampling_rate=8000, channel=1
  16.     fout.write(pack('>4s5L', '.snd'.encode("utf8"), 24, 8*dur, 2, 8000, 1))
  17.     factor = 2 * pi * freq/8000
  18.     # write data
  19.     for seg in range(8 * dur):
  20.         # sine wave calculations
  21.         sin_seg = sin(seg * factor)
  22.         val = pack('b', int(vol * 127 * sin_seg))
  23.         fout.write(val)
  24.     fout.close()
  25.     print("File %s written" % name)
  26. # test the module ...
  27. if __name__ == '__main__':
  28.     au_file(name=dir+'sound440.au', freq=440, dur=2000, vol=0.8)
  29.     # if you have Windows, you can test the audio file
  30.     # otherwise comment this code out
  31.     import os
  32.     os.startfile(dir+'sound440.au')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement