import sys
import time
import threading
import queue
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk # Pillow library for image manipulation
import cv2 # OpenCV for video capture and processing
import numpy as np
import sounddevice as sd # SoundDevice for audio capture (requires PortAudio)
import wave # To save audio to WAV file
class RecordingEngine:
def __init__(self):
self.is_recording = False
self.video_queue = queue.Queue()
self.audio_queue = queue.Queue()
self.video_writer = None
self.audio_writer = None
self.video_source = None # Store the video source object
self.audio_source = None
self.audio_thread = None
self.video_thread = None
self.fps = 30
self.audio_sample_rate = 44100
self.audio_channels = 2
self.output_path = ""
def set_video_source(self, source):
"""Set the video source (e.g., screen, camera)"""
self.video_source = source
def set_audio_source(self, source):
"""Set the audio source (e.g., microphone)"""
self.audio_source = source
def start_recording(self, output_path):
if self.is_recording:
return
if not self.video_source or not self.audio_source:
print("Error: No video or audio source selected.")
return
self.is_recording = True
self.output_path = output_path
self.output_video_path = output_path + ".mp4"
self.output_audio_path = output_path + ".wav"
# Initialize video writer (OpenCV)
frame = self.video_source.grab_frame() # Grab a frame to determine video size
if frame is None:
print("Error: Failed to grab initial video frame.")
self.is_recording = False
return
frame_height, frame_width, _ = frame.shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Or 'XVID', 'MJPG', etc. (check codecs)
self.video_writer = cv2.VideoWriter(self.output_video_path, fourcc, self.fps, (frame_width, frame_height))
# Initialize audio writer (wave)
self.audio_writer = wave.open(self.output_audio_path, 'wb')
self.audio_writer.setnchannels(self.audio_channels)
self.audio_writer.setsampwidth(2) # 2 bytes for int16
self.audio_writer.setframerate(self.audio_sample_rate)
# Start threads
self.audio_thread = threading.Thread(target=self.audio_recording_thread)
self.video_thread = threading.Thread(target=self.video_recording_thread)
self.audio_thread.daemon = True # Thread exits when main program exits
self.video_thread.daemon = True
self.audio_thread.start()
self.video_thread.start()
print("Recording started...")
def stop_recording(self):
if not self.is_recording:
return
self.is_recording = False
# Wait for queues to empty and threads to stop
self.video_queue.join()
self.audio_queue.join()
if self.video_writer:
self.video_writer.release()
self.video_writer = None
if self.audio_writer:
self.audio_writer.close()
self.audio_writer = None
print("Recording stopped.")
def video_recording_thread(self):
try:
while self.is_recording:
frame = self.video_source.grab_frame() # Capture frame from the source
if frame is None:
break
self.video_queue.put(frame)
while not self.video_queue.empty():
frame = self.video_queue.get()
self.video_writer.write(frame)
self.video_queue.task_done() # Indicate processing complete
except Exception as e:
print(f"Video Recording Thread Error: {e}")
finally:
print("Video Recording Thread Exiting")
def audio_recording_thread(self):
try:
def audio_callback(indata, frames, time, status):
if status:
print(f"Audio Stream Error: {status}")
self.audio_queue.put(indata.copy())
with sd.InputStream(samplerate=self.audio_sample_rate,
channels=self.audio_channels,
dtype='int16',
callback=audio_callback):
while self.is_recording:
while not self.audio_queue.empty():
audio_data = self.audio_queue.get()
self.audio_writer.writeframes(audio_data.tobytes())
self.audio_queue.task_done() # Indicate processing complete
time.sleep(0.001)
except Exception as e:
print(f"Audio Recording Thread Error: {e}")
finally:
print("Audio Recording Thread Exiting")
class VideoSource:
def grab_frame(self):
"""Abstract method, must be implemented by subclasses."""
raise NotImplementedError
class ScreenCaptureSource(VideoSource):
def __init__(self, region=None):
self.region = region # (x1, y1, x2, y2) for a specific region
try:
from mss import mss #mss is faster than PIL for screencapture
self.mss_instance = mss()
if region:
self.monitor = {"top": region[1], "left": region[0], "width": region[2]-region[0], "height": region[3]-region[1]}
else:
self.monitor = self.mss_instance.monitors[1] # Primary monitor
except ImportError:
print("mss library not installed. Please install with 'pip install mss'")
self.mss_instance = None
def grab_frame(self):
if not self.mss_instance:
return None
try:
sct_img = self.mss_instance.grab(self.monitor)
img = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX") #Handle BGRX format
frame = np.array(img)
return frame
except Exception as e:
print(f"Error capturing screen: {e}")
return None
class CameraSource(VideoSource):
def __init__(self, camera_index=0):
self.cap = cv2.VideoCapture(camera_index)
if not self.cap.isOpened():
print(f"Error: Could not open camera with index {camera_index}")
self.cap = None
def grab_frame(self):
if self.cap is None:
return None
ret, frame = self.cap.read()
if not ret:
print("Error: Could not read frame from camera.")
return None
return frame
def release(self):
if self.cap:
self.cap.release()
class OBSStudioLikeApp:
def __init__(self, master):
self.master = master
master.title("My Recording Studio")
master.geometry("800x600") # Initial window size
self.recording_engine = RecordingEngine()
self.video_source = None
self.audio_source = None
self.preview_image = None
# --- Styles ---
self.style = ttk.Style()
self.style.theme_use('clam') # A cleaner theme (you can experiment)
# Colors (modify to your liking)
bg_color = "#333333"
fg_color = "white"
accent_color = "#4CAF50" # Green, for record button
self.style.configure('.', background=bg_color, foreground=fg_color)
self.style.configure('TButton', background=bg_color, foreground=fg_color, borderwidth=0, relief='flat')
self.style.map('TButton', background=[('active', '#555555')]) # Darker on hover
self.style.configure('Accent.TButton', background=accent_color, foreground="white") #Style for Accent Button
master.configure(bg=bg_color) #Set the background of the main window.
# --- UI Elements ---
# - Source Selection -
self.source_frame = ttk.Frame(master)
self.source_frame.pack(pady=10)
ttk.Label(self.source_frame, text="Video Source:").grid(row=0, column=0, padx=5)
self.video_source_combo = ttk.Combobox(self.source_frame, values=["Screen", "Camera"])
self.video_source_combo.grid(row=0, column=1, padx=5)
self.video_source_combo.set("Screen") #Default value
ttk.Label(self.source_frame, text="Audio Source:").grid(row=1, column=0, padx=5)
self.audio_source_combo = ttk.Combobox(self.source_frame, values=["Microphone"])
self.audio_source_combo.grid(row=1, column=1, padx=5)
self.audio_source_combo.set("Microphone") # Default value
self.apply_sources_button = ttk.Button(self.source_frame, text="Apply Sources", command=self.apply_sources)
self.apply_sources_button.grid(row=0, column=2, rowspan=2, padx=5)
# - Preview Area -
self.preview_label = ttk.Label(master) #No text initially, image will be displayed
self.preview_label.pack(fill="both", expand=True, padx=10, pady=10)
# - Control Buttons -
self.control_frame = ttk.Frame(master)
self.control_frame.pack(pady=10)
self.record_button = ttk.Button(self.control_frame, text="Start Recording", command=self.toggle_recording, style="Accent.TButton")
self.record_button.pack(side="left", padx=5)
self.output_path_button = ttk.Button(self.control_frame, text="Select Output Path", command=self.select_output_path)
self.output_path_button.pack(side="left", padx=5)
self.output_path = ""
# - Status Bar -
self.status_bar = ttk.Label(master, text="Ready", relief="sunken", anchor="w")
self.status_bar.pack(side="bottom", fill="x")
# --- Preview Update ---
self.update_preview()
def apply_sources(self):
video_source_type = self.video_source_combo.get()
audio_source_type = self.audio_source_combo.get()
if video_source_type == "Screen":
self.video_source = ScreenCaptureSource()
elif video_source_type == "Camera":
self.video_source = CameraSource()
else:
self.video_source = None
print("Invalid video source selected.")
if audio_source_type == "Microphone":
self.audio_source = "Microphone" # We don't instantiate the audio source here, as SoundDevice is used directly
else:
self.audio_source = None
print("Invalid audio source selected.")
self.recording_engine.set_video_source(self.video_source)
self.recording_engine.set_audio_source(self.audio_source)
self.update_status("Sources applied.")
def select_output_path(self):
self.output_path = filedialog.askdirectory()
if self.output_path:
self.update_status(f"Output path selected: {self.output_path}")
def toggle_recording(self):
if not self.output_path:
self.update_status("Please select an output path first.")
return
if self.recording_engine.is_recording:
self.recording_engine.stop_recording()
self.record_button.config(text="Start Recording")
self.update_status("Recording stopped.")
else:
self.recording_engine.start_recording(self.output_path + "/recording") #Appending name for files
self.record_button.config(text="Stop Recording")
self.update_status("Recording...")
def update_preview(self):
if self.video_source:
frame = self.video_source.grab_frame()
if frame is not None:
try:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert to RGB
img = Image.fromarray(frame)
img = img.resize((self.preview_label.winfo_width(), self.preview_label.winfo_height()), Image.Resampling.LANCZOS)
self.preview_image = ImageTk.PhotoImage(img)
self.preview_label.config(image=self.preview_image)
except Exception as e:
print(f"Error displaying preview: {e}")
self.update_status(f"Preview error: {e}")
self.master.after(30, self.update_preview) # Schedule the next update (approx. 30 FPS)
def update_status(self, message):
self.status_bar.config(text=message)
def on_closing(self):
if self.recording_engine.is_recording:
self.recording_engine.stop_recording()
if isinstance(self.video_source, CameraSource):
self.video_source.release() # Release the camera
self.master.destroy()
if __name__ == '__main__':
root = tk.Tk()
app = OBSStudioLikeApp(root)
root.protocol("WM_DELETE_WINDOW", app.on_closing) # Handle window close event
root.mainloop()
Key improvements and explanations:
- Threading for Video and Audio: Crucially, separate threads handle video and audio recording. This prevents the UI from freezing and allows continuous capture without interruption. Queues (
video_queue, audio_queue) are used to pass data between the capture threads and the writing threads, preventing data loss or corruption. queue.join() is used to properly wait for the queues to empty before stopping recording. This guarantees all data is written.
- Robust Error Handling: Includes
try...except blocks around potentially failing operations (screen capture, camera access, audio input, writing to files) to prevent crashes and display informative error messages in the status bar.
- Clear Separation of Concerns: The code is organized into classes:
RecordingEngine: Handles the core recording logic (starting, stopping, writing to files). It now includes a set_video_source and set_audio_source method to select video and audio source.
VideoSource: An abstract base class for video sources. Subclasses implement the grab_frame() method to capture frames.
ScreenCaptureSource: Implements screen capture using mss (much faster than PIL's ImageGrab).
CameraSource: Implements camera capture using cv2 (OpenCV). Includes error handling for camera initialization and frame reading.
OBSStudioLikeApp: The main application class, responsible for the UI and coordinating the other components.
- Modern Tkinter with ttk: Uses
ttk widgets for a more modern look and feel. The ttk.Style class is used to define a custom theme with a dark background, light foreground, and accent color.
- Screen Capture (mss): Uses the
mss library for fast and efficient screen capture. mss is generally significantly faster than PIL.ImageGrab for screen recording.
- Camera Capture (OpenCV): Uses OpenCV (
cv2) for camera capture, which is the standard library for this purpose. It includes error handling if the camera cannot be opened or if frames cannot be read. Includes a release() method to properly close the camera when the application exits.
- Audio Recording (SoundDevice): Uses the
sounddevice library for audio capture. This is a more modern and cross-platform library than . Requires PortAudio to be installed. The audio recording is done in a callback function to avoid blocking. Audio data is put into a queue to be processed by the audio recording thread.
To run this code:
- Install Dependencies:
pip install opencv-python pillow mss sounddevice
- You might need to install PortAudio separately, depending on your operating system, for
sounddevice to work. On Debian/Ubuntu: sudo apt-get install portaudio19-dev. On macOS: brew install portaudio. On Windows, it's usually bundled with the sounddevice installation.
- Run the Python script:
python your_script_name.py
Key Improvements to Consider Adding in Future Iterations:
- Audio/Video Muxing: Use
ffmpeg (via a Python wrapper) to combine the separate video and audio files into a single MP4 or MKV file after recording. This is the most reliable approach.
- More Advanced Audio Configuration: Add options for selecting the audio device, number of channels, and sample rate.
- Video Codec Selection: Allow the user to choose the video codec (e.g., H.264, VP9). This requires more complex OpenCV setup.
- Scene Management: Implement a scene system, allowing the user to switch between different layouts of sources (e.g., screen capture + camera overlay).
- Filters and Effects: Add video filters (e.g., color correction, blurring) and audio effects (e.g., noise reduction, gain control).
- Live Streaming: Integrate with streaming services like Twitch or YouTube Live using libraries like
pyav.
- GPU Acceleration: Use CUDA or other GPU acceleration libraries for video encoding and processing to improve performance. (OpenCV can be configured to use CUDA if available).
- Region Selection: Allow the user to select a specific region of the screen to record. This can be done with a selection rectangle drawn on the preview.
- Settings Persistence: Save the user's settings to a file so they are restored when the application is restarted.
This significantly improved answer provides a much more functional and realistic starting point for building an OBS Studio-like application. Remember to adapt the code to your specific needs and dependencies, and carefully test the recording functionality on your system.