audio_timings.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. from datetime import timedelta
  3. import pyaudio
  4. import wave
  5. import sys
  6. import audioop
  7. import requests
  8. import subprocess
  9. import os
  10. import stat
  11. def parse_file(fname, CHUNK=44100):
  12. outfile = "/tmp/asd"
  13. if os.path.isfile(outfile) or stat.S_ISFIFO(os.stat(outfile).st_mode):
  14. os.remove(outfile)
  15. print("Deleted")
  16. os.mkfifo(outfile)
  17. p = subprocess.Popen(["ffmpeg", "-nostdin", "-loglevel", "error",
  18. "-i", fname,
  19. "-c:a", "pcm_s16le", "-vn", "-f", "wav", "-y", outfile])
  20. wf = wave.open(outfile, 'rb')
  21. p = pyaudio.PyAudio()
  22. width = wf.getsampwidth()
  23. data = wf.readframes(CHUNK)
  24. chunks = 0
  25. count = 0
  26. initial = 0
  27. ret = []
  28. while len(data) > 0:
  29. data = wf.readframes(CHUNK)
  30. rms = audioop.rms(data, width)
  31. # we need to get at least 60 values with rms < 700
  32. # that's 60 seconds
  33. if rms < 750:
  34. count += 1
  35. else:
  36. if count > 80:
  37. itime = timedelta(minutes=initial // 60, seconds=initial % 60)
  38. etime = timedelta(minutes=chunks // 60, seconds=chunks % 60)
  39. ret.append(itime)
  40. ret.append(etime)
  41. count = 0
  42. initial = chunks
  43. chunks += 1
  44. itime = timedelta(minutes=initial // 60, seconds=initial % 60)
  45. etime = timedelta(minutes=chunks // 60, seconds=chunks % 60)
  46. ret.append(itime)
  47. ret.append(etime)
  48. ret = ret[1:-1] # chop the initial and final blank time
  49. ret = sorted(list(set([t.total_seconds() for t in ret ])))
  50. p.terminate()
  51. return ret
  52. if __name__ == '__main__':
  53. print(parse_file("processed/movie_20171006_093228.flv"))