Guest User

Untitled

a guest
Nov 23rd, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.55 KB | None | 0 0
  1. import cv2
  2. import pyaudio
  3. import wave
  4. import threading
  5. import time
  6. import subprocess
  7. import os
  8. from datetime import datetime
  9. class VideoRecorder():
  10. from datetime import datetime
  11.  
  12.  
  13. # Video class based on openCV
  14. def __init__(self):
  15. datestring = datetime.strftime(datetime.now(), '%Y-%m-%d-%H-%M-%S')
  16. # f = open('myfile_' + datestring + '.ext', 'w')
  17.  
  18.  
  19.  
  20. #os.system('ffmpeg -y -t 00:00:12 -f dshow -i video="Logitech HD Webcam C270" kamera' + datestring + '.mp4')
  21.  
  22. self.open = True
  23. self.device_index = 0
  24. self.fps = 30 # fps should be the minimum constant rate at which the camera can
  25. self.fourcc = "MJPG" # capture images (with no decrease in speed over time; testing is required)
  26. self.frameSize = (640,480) # video formats and sizes also depend and vary according to the camera used
  27. self.video_filename = ("kamera"+ datestring +".mp4")
  28. self.video_cap = cv2.VideoCapture(self.device_index)
  29. self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc)
  30. self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize)
  31. self.frame_counts = 1
  32. self.start_time = time.time()
  33.  
  34.  
  35.  
  36. # Video starts being recorded
  37. def record(self):
  38.  
  39. # counter = 1
  40. timer_start = time.time()
  41. timer_current = 0
  42.  
  43.  
  44. while(self.open==True):
  45. ret, video_frame = self.video_cap.read()
  46. if (ret==True):
  47.  
  48. self.video_out.write(video_frame)
  49. # print str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current)
  50. self.frame_counts += 1
  51. # counter += 1
  52. # timer_current = time.time() - timer_start
  53. time.sleep(0.16)
  54. # gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY)
  55. # cv2.imshow('video_frame', gray)
  56. # cv2.waitKey(1)
  57. else:
  58. break
  59.  
  60. # 0.16 delay -> 6 fps
  61. #
  62.  
  63.  
  64. # Finishes the video recording therefore the thread too
  65. def stop(self):
  66.  
  67. if self.open==True:
  68.  
  69. self.open=False
  70. self.video_out.release()
  71. self.video_cap.release()
  72. cv2.destroyAllWindows()
  73.  
  74. else:
  75. pass
  76.  
  77.  
  78. # Launches the video recording function using a thread
  79. def start(self):
  80. video_thread = threading.Thread(target=self.record)
  81. video_thread.start()
  82.  
  83.  
  84.  
  85.  
  86.  
  87. class AudioRecorder():
  88.  
  89.  
  90. # Audio class based on pyAudio and Wave
  91. def __init__(self):
  92.  
  93. self.open = True
  94. self.rate = 44100 #bilo je: self.rate = 44100
  95. self.frames_per_buffer = 1024 #bilo je: self.frames_per_buffer = 1024
  96. self.channels = 2
  97. self.format = pyaudio.paInt16
  98. self.audio_filename = "temp_audio.wav"
  99. self.audio = pyaudio.PyAudio()
  100. self.stream = self.audio.open(format=self.format,
  101. channels=self.channels,
  102. rate=self.rate,
  103. input=True,
  104. frames_per_buffer = self.frames_per_buffer)
  105. self.audio_frames = []
  106.  
  107.  
  108. # Audio starts being recorded
  109. def record(self):
  110.  
  111. self.stream.start_stream()
  112. while(self.open == True):
  113. data = self.stream.read(self.frames_per_buffer)
  114. self.audio_frames.append(data)
  115. if self.open==False:
  116. break
  117.  
  118.  
  119. # Finishes the audio recording therefore the thread too
  120. def stop(self):
  121.  
  122. if self.open==True:
  123. self.open = False
  124. self.stream.stop_stream()
  125. self.stream.close()
  126. self.audio.terminate()
  127.  
  128. waveFile = wave.open(self.audio_filename, 'wb')
  129. waveFile.setnchannels(self.channels)
  130. waveFile.setsampwidth(self.audio.get_sample_size(self.format))
  131. waveFile.setframerate(self.rate)
  132. waveFile.writeframes(b''.join(self.audio_frames))
  133. waveFile.close()
  134.  
  135. pass
  136.  
  137. # Launches the audio recording function using a thread
  138. def start(self):
  139. audio_thread = threading.Thread(target=self.record)
  140. audio_thread.start()
  141.  
  142.  
  143.  
  144.  
  145.  
  146. def start_AVrecording(filename):
  147.  
  148. global video_thread
  149. global audio_thread
  150.  
  151. video_thread = VideoRecorder()
  152. audio_thread = AudioRecorder()
  153.  
  154. audio_thread.start()
  155. video_thread.start()
  156.  
  157. return filename
  158.  
  159.  
  160.  
  161.  
  162. def start_video_recording(filename):
  163.  
  164. global video_thread
  165.  
  166. video_thread = VideoRecorder()
  167. video_thread.start()
  168.  
  169. return filename
  170.  
  171.  
  172. def start_audio_recording(filename):
  173.  
  174. global audio_thread
  175.  
  176. audio_thread = AudioRecorder()
  177. audio_thread.start()
  178.  
  179. return filename
  180.  
  181.  
  182.  
  183.  
  184. def stop_AVrecording(filename):
  185.  
  186. audio_thread.stop()
  187. frame_counts = video_thread.frame_counts
  188. elapsed_time = time.time() - video_thread.start_time
  189. recorded_fps = frame_counts / elapsed_time
  190. print("total frames " + str(frame_counts))
  191. print ("elapsed time " + str(elapsed_time))
  192. print ("recorded fps " + str(recorded_fps))
  193. video_thread.stop()
  194.  
  195. # Makes sure the threads have finished
  196. while threading.active_count() > 1:
  197. time.sleep(1)
  198.  
  199.  
  200. # Merging audio and video signal
  201.  
  202. if abs(recorded_fps - 6) >= 0.01: # If the fps rate was higher/lower than expected, re-encode it to the expected
  203.  
  204. print ("Re-encoding")
  205. cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi"
  206. subprocess.call(cmd, shell=True)
  207.  
  208. print ("Muxing")
  209. cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi"
  210. subprocess.call(cmd, shell=True)
  211.  
  212. else:
  213.  
  214. print ("Normal recordingnMuxing")
  215. cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi"
  216. subprocess.call(cmd, shell=True)
  217.  
  218. print ("..")
  219.  
  220.  
  221.  
  222.  
  223. # Required and wanted processing of final files
  224. def file_manager(filename):
  225.  
  226. local_path = os.getcwd()
  227.  
  228. if os.path.exists(str(local_path) + "/temp_audio.wav"):
  229. os.remove(str(local_path) + "/temp_audio.wav")
  230.  
  231. if os.path.exists(str(local_path) + "/temp_video.avi"):
  232. os.remove(str(local_path) + "/temp_video.avi")
  233.  
  234. if os.path.exists(str(local_path) + "/temp_video2.avi"):
  235. os.remove(str(local_path) + "/temp_video2.avi")
  236.  
  237. if os.path.exists(str(local_path) + "/" + filename + ".avi"):
  238. os.remove(str(local_path) + "/" + filename + ".avi")
Add Comment
Please, Sign In to add comment