import cv2 import numpy as np import os import mss import time import subprocess import…
- User
import cv2 import numpy as np import os import mss import time import subprocess import queue import sounddevice as sd import soundfile as sf from tkinter import Tk, filedialog # --- Configuration --- FPS = 15.0 # Desired frames per second. CAMERA_INDEX = 0 # 0 for default camera. Change if you have multiple cameras. CAMERA_SCALE = 0.25 # Scale of the camera overlay in the final video. CHANNELS = 1 # 1 for mono audio. RATE = 44100 # Standard audio sample rate. class AudioRecorder: """A class to handle audio recording using sounddevice.""" def init(self, filename="temp_audio.wav", rate=RATE, channels=CHANNELS): self.filename = filename self.rate = rate self.channels = channels self.audio_queue = queue.Queue() self.stream = None def _callback(self, indata, frames, time, status): """This is called by sounddevice for each audio block.""" if status: print(f"Audio Error: {status}") self.audio_queue.put(indata.copy()) def start(self): """Starts the audio recording stream.""" self.stream = sd.InputStream( samplerate=self.rate, channels=self.channels, callback=self._callback, dtype='int16' ) self.stream.start() print("Audio recording started.") def stop(self): """Stops recording and saves the audio to a file.""" if self.stream: self.stream.stop() self.stream.close() print("Audio recording stopped.") frames = [] while not self.audio_queue.empty(): frames.append(self.audio_queue.get()) if frames: audio_data = np.concatenate(frames, axis=0) sf.write(self.filename, audio_data, self.rate) print(f"Temporary audio saved to {self.filename}") else: print("Warning: No audio data was captured.") def get_save_path(): """Opens a dialog to ask the user for the save file path.""" root = Tk() root.withdraw() root.attributes('-topmost', True) filepath = filedialog.asksaveasfilename( title="Save recording as...", defaultextension=".mp4", filetypes=[("MP4 files", ".mp4"), ("All files", ".")] ) root.destroy() return filepath def combine_audio_video(video_path, audio_path, output_path): """Combines video and audio files into a single MP4 using FFmpeg.""" print("Combining audio and video with FFmpeg...") try: subprocess.run(["ffmpeg", "-version"], check=True, capture_output=True, text=True) except (subprocess.CalledProcessError, FileNotFoundError): print("\nERROR: FFmpeg not found. Please install it and ensure it's in your system's PATH.") return False command = [ 'ffmpeg', '-y', '-i', video_path, '-i', audio_path, '-c:v', 'libx264', '-preset', 'fast', '-crf', '22', '-c:a', 'aac', '-b:a', '192k', '-shortest', output_path ] try: subprocess.run(command, check=True, capture_output=True, text=True) print(f"✅ Successfully saved recording to {output_path}") return True except subprocess.CalledProcessError as e: print(f"\nERROR: FFmpeg failed to combine files.\nFFmpeg stderr:\n{e.stderr}") return False def main(): """Main function to run the headless recorder with a separate camera preview.""" output_filename = get_save_path() if not output_filename: print("No file selected. Exiting.") return temp_video_filename = "temp_video.avi" temp_audio_filename = "temp_audio.wav" sct = mss.mss() monitor = sct.monitors[1] cap = cv2.VideoCapture(CAMERA_INDEX) if not cap.isOpened(): print("Error: Could not open camera.") return screen_width, screen_height = monitor['width'], monitor['height'] cam_width, cam_height = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) new_cam_width = int(screen_width * CAMERA_SCALE) new_cam_height = int(cam_height * (new_cam_width / cam_width)) fourcc = cv2.VideoWriter_fourcc('XVID') out = cv2.VideoWriter(temp_video_filename, fourcc, FPS, (screen_width, screen_height)) audio_recorder = AudioRecorder(temp_audio_filename) audio_recorder.start() print("\n🔴 Recording started! Press Ctrl+C in this terminal to stop.") try: while True: # Capture the screen sct_img = sct.grab(monitor) screen_frame = np.array(sct_img) screen_frame = cv2.cvtColor(screen_frame, cv2.COLOR_BGRA2BGR) # Capture the camera feed ret, cam_frame = cap.read() if not ret: # If camera fails, create a black placeholder cam_frame = np.zeros((cam_height, cam_width, 3), dtype=np.uint8) # --- NEW: Show the live camera preview in a separate window --- cv2.imshow('My Camera Preview', cam_frame) # We need a small wait key (1 ms) for the window to update cv2.waitKey(1) # ----------------------------------------------------------- # Resize camera frame for overlaying on the main video cam_frame_resized = cv2.resize(cam_frame, (new_cam_width, new_cam_height)) # Position for the overlay (bottom-right) y_offset = screen_height - new_cam_height - 20 x_offset = screen_width - new_cam_width - 20 # Overlay the camera onto the screen recording screen_frame[y_offset:y_offset+new_cam_height, x_offset:x_offset+new_cam_width] = cam_frame_resized # Write the combined frame to the video file out.write(screen_frame) except KeyboardInterrupt: print("\nStopping recording due to user request (Ctrl+C).") finally: # Clean up all resources out.release() cap.release() cv2.destroyAllWindows() # Closes the camera preview window print("Temporary video saved.") audio_recorder.stop() # Combine the video and audio files if os.path.exists(temp_video_filename) and os.path.getsize(temp_video_filename) > 0: if combine_audio_video(temp_video_filename, temp_audio_filename, output_filename): print("Cleaning up temporary files...") try: os.remove(temp_video_filename) os.remove(temp_audio_filename) print("Cleanup complete.") except OSError as e: print(f"Error cleaning up temporary files: {e}") else: print("\nCould not create the final video.") print("You can find the raw streams here:") print(f"Video: {os.path.abspath(temp_video_filename)}") print(f"Audio: {os.path.abspath(temp_audio_filename)}") else: print("No video was recorded.") if == "": print("="*60) print("Headless Recorder with Separate Camera Preview") print("="*60) main()
Assistant
- User
help me fix this error please Traceback (most recent call last): File "/home/samer/Desktop/Beedoo/video recording/recorder.py", line 143, in main cv2.imshow('My Camera Preview', cam_frame) cv2.error: OpenCV(4.11.0) /io/opencv/modules/highgui/src/window.cpp:1301: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/samer/Desktop/Beedoo/video recording/recorder.py", line 195, in main() File "/home/samer/Desktop/Beedoo/video recording/recorder.py", line 167, in main cv2.destroyAllWindows() # Closes the camera preview window ^^^^^^^^^^^^^^^^^^^^^^^ cv2.error: OpenCV(4.11.0) /io/opencv/modules/highgui/src/window.cpp:1295: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvDestroyAllWindows'
Assistant