Advertisement
here2share

# tones.py

Oct 5th, 2022
741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. # tones.py
  2.  
  3. import math
  4. import wave
  5. import struct
  6.  
  7. audio = []
  8. sample_rate = 44100.0
  9. dir = 'C://py//audio//'
  10.  
  11. def append_silence(duration_milliseconds=500):
  12.     """
  13.    Adding silence is easy - we add zeros to the end of our array
  14.    """
  15.     num_samples = duration_milliseconds * (sample_rate / 1000.0)
  16.  
  17.     for x in range(int(num_samples)):
  18.         audio.append(0.0)
  19.  
  20.  
  21. def append_sinewave(
  22.         freq=440.0,
  23.         duration_milliseconds=500,
  24.         volume=1.0):
  25.  
  26.     num_samples = duration_milliseconds * (sample_rate / 1000.0)
  27.  
  28.     for x in range(int(num_samples)):
  29.         audio.append(volume * math.sin(2 * math.pi * freq * ( x / sample_rate )))
  30.  
  31.  
  32. def save_wav(file_name):
  33.     # open up a mp3 file
  34.     mp3_file=wave.open(dir+file_name+".mp3","w")
  35.  
  36.     # wav params
  37.     nchannels = 1
  38.  
  39.     sampwidth = 2
  40.  
  41.     # 44100 is the industry standard sample rate - CD quality.
  42.     nframes = len(audio)
  43.     comptype = "NONE"
  44.     compname = "not compressed"
  45.     mp3_file.setparams((nchannels, sampwidth, sample_rate, nframes, comptype, compname))
  46.  
  47.     for sample in audio:
  48.         mp3_file.writeframes(struct.pack('h', int( sample * 32767.0 )))
  49.  
  50.     mp3_file.close()
  51.  
  52. def noteToFreq(note):
  53.     a = 440 # common value frequency is 440Hz
  54.     return (a / 32.) * (2 ** ((note - 9.) / 12))
  55.  
  56. audio = []
  57. for _ in range(8):
  58.     append_sinewave(freq=noteToFreq(80),duration_milliseconds=30)
  59.     append_sinewave(freq=noteToFreq(85),duration_milliseconds=60)
  60.     append_sinewave(freq=noteToFreq(90),duration_milliseconds=30)
  61. append_silence(duration_milliseconds=150)
  62. save_wav("testing")
  63.  
  64. notes = [45, 47, 48, 50, 52, 53, 55, 57, 59, 60, 62, 64, 65, 67, 69]
  65.  
  66. for i in range(len(notes)):
  67.     audio = []
  68.     append_sinewave(freq=noteToFreq(notes[i]+12),duration_milliseconds=200)
  69.     save_wav("note"+str(i+1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement