wavstat.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env python3
  2. """wavstat.py <file.wav> [window seconds] - per channel peak/RMS and, per window, RMS of each channel.
  3. Reads the float32 or int16 WAVs parec writes (audio_sink.sh record)."""
  4. import struct, sys
  5. import numpy as np
  6. def read_wav(path):
  7. d = open(path, 'rb').read()
  8. pos, fmt, data = 12, None, None
  9. while pos + 8 <= len(d):
  10. tag, size = d[pos:pos + 4], struct.unpack('<I', d[pos + 4:pos + 8])[0]
  11. body = d[pos + 8:pos + 8 + size] if size != 0xFFFFFFFF else d[pos + 8:]
  12. if tag == b'fmt ':
  13. fmt = struct.unpack('<HHIIHH', body[:16])
  14. elif tag == b'data':
  15. data = body
  16. break
  17. pos += 8 + size + (size & 1)
  18. code, channels, rate, _, _, bits = fmt
  19. dtype = '<f4' if code == 3 or (code == 0xFFFE and bits == 32) else '<i2'
  20. a = np.frombuffer(data[:len(data) // (channels * bits // 8) * channels * bits // 8], dtype=dtype)
  21. a = a.astype(np.float64) / (32768.0 if dtype == '<i2' else 1.0)
  22. return a.reshape(-1, channels), rate
  23. if __name__ == '__main__':
  24. a, rate = read_wav(sys.argv[1])
  25. print('%s: %.2f s, %d Hz, %d ch' % (sys.argv[1], len(a) / rate, rate, a.shape[1]))
  26. print('peak', np.abs(a).max(0).round(4), 'rms', np.sqrt((a ** 2).mean(0)).round(4))
  27. if len(sys.argv) > 2:
  28. n = int(float(sys.argv[2]) * rate)
  29. for i in range(0, len(a), n):
  30. w = a[i:i + n]
  31. print('%7.2f s ' % (i / rate) + ' '.join('%.4f' % v for v in np.sqrt((w ** 2).mean(0))))