Below is an example of how to set up a Raspberry Pi to record both video and audio using the Raspberry Pi NoIR Camera Module and an external USB microphone.
- Raspberry Pi with Raspbian OS installed
- Raspberry Pi NoIR Camera Module
- USB microphone
- Python installed on the Raspberry Pi
- Connect the NoIR Camera Module to the Raspberry Pi.
- Connect the USB microphone to one of the USB ports on the Raspberry Pi.
- Enable the camera module on your Raspberry Pi by running
sudo raspi-config
and selectingInterfacing Options
->Camera
->Enable
.
First, install the necessary libraries:
sudo apt-get update
sudo apt-get install python3-picamera python3-pyaudio ffmpeg
pip3 install sounddevice
Create a Python script to record video and audio simultaneously:
import time
import subprocess
import sounddevice as sd
import numpy as np
from datetime import datetime
from picamera import PiCamera
# Configuration
VIDEO_DURATION = 12 * 60 * 60 # Record for 12 hours (in seconds)
VIDEO_FILENAME = 'video.h264'
AUDIO_FILENAME = 'audio.wav'
FINAL_OUTPUT_FILENAME = 'output_with_audio.mp4'
SAMPLERATE = 44100
# Record video
def record_video():
camera = PiCamera()
camera.resolution = (1920, 1080)
camera.start_recording(VIDEO_FILENAME)
camera.wait_recording(VIDEO_DURATION)
camera.stop_recording()
camera.close()
# Record audio
def record_audio():
recording = sd.rec(int(VIDEO_DURATION * SAMPLERATE), samplerate=SAMPLERATE, channels=2, dtype='int16')
sd.wait()
# Save as WAV file
np.savetxt(AUDIO_FILENAME, recording, fmt='%d')
# Combine audio and video using ffmpeg
def combine_audio_video():
command = f'ffmpeg -y -i {VIDEO_FILENAME} -i {AUDIO_FILENAME} -c:v copy -c:a aac {FINAL_OUTPUT_FILENAME}'
subprocess.call(command, shell=True)
# Main function to record video and audio simultaneously
if __name__ == "__main__":
start_time = datetime.now()
print(f"Recording started at {start_time}")
# Start recording video and audio
record_video()
record_audio()
# Combine the recorded video and audio
combine_audio_video()
end_time = datetime.now()
print(f"Recording finished at {end_time}")
print(f"Output saved as {FINAL_OUTPUT_FILENAME}")
- The
record_video
function uses thepicamera
library to record video from the Raspberry Pi NoIR Camera Module. - The
record_audio
function uses thesounddevice
library to record audio from a USB microphone. - The
combine_audio_video
function usesffmpeg
to combine the recorded video and audio into a single file.
Save the script as record.py
and run it using:
python3 record.py
This script will record both video and audio simultaneously for 12 hours and save the combined output as output_with_audio.mp4
. Adjust the VIDEO_DURATION
as needed for your project.