Advertisement
Guest User

Untitled

a guest
Feb 25th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. import wave
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import matplotlib.ticker as ticker
  5. import math
  6.  
  7. types = {
  8.     1: np.int8,
  9.     2: np.int16,
  10.     4: np.int32
  11. }
  12.  
  13.  
  14. def format_time(x, pos=None):
  15.     global duration, nframes, k
  16.     progress = int(x / float(nframes) * duration * k)
  17.     mins, secs = divmod(progress, 60)
  18.     hours, mins = divmod(mins, 60)
  19.     out = "%d:%02d" % (mins, secs)
  20.     if hours > 0:
  21.         out = "%d:" % hours
  22.     return out
  23.  
  24.  
  25. def format_db(x, pos=None):
  26.     if pos == 0:
  27.         return ""
  28.     global peak
  29.     if x == 0:
  30.         return "-inf"
  31.  
  32.     db = 20 * math.log10(abs(x) / float(peak))
  33.     return int(db)
  34.  
  35. wav = wave.open("E:\\output.wav", mode="r")
  36. (nchannels, sampwidth, framerate, nframes, comptype, compname) = wav.getparams()
  37. print(nchannels, sampwidth, framerate, nframes, comptype, compname)
  38. duration = nframes / framerate
  39. w, h = 800, 300
  40. k = int(nframes/w/32)
  41. DPI = 72
  42. peak = 256 ** sampwidth / 2
  43.  
  44. content = wav.readframes(nframes)
  45. samples = np.fromstring(content, dtype=types[sampwidth])
  46.  
  47. plt.figure(1, figsize=(float(w)/DPI, float(h)/DPI), dpi=DPI)
  48. plt.subplots_adjust(wspace=0, hspace=0)
  49.  
  50. for n in range(nchannels):
  51.     channel = samples[n:nchannels * 500 + n:nchannels]
  52.  
  53.     # channel = channel[0::k]
  54.     if nchannels == 1:
  55.         channel = channel - peak
  56.  
  57.     axes = plt.subplot(2, 1, n+1, axisbg="k")
  58.     axes.plot(channel, "g")
  59.     axes.yaxis.set_major_formatter(ticker.FuncFormatter(format_db))
  60.     plt.grid(True, color="w")
  61.     axes.xaxis.set_major_formatter(ticker.NullFormatter())
  62.  
  63. axes.xaxis.set_major_formatter(ticker.FuncFormatter(format_time))
  64. plt.savefig("wave", dpi=DPI)
  65. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement