Skip to main content

Recipe for recording webcam and microphone using ffmpeg in GNU/Linux

Oftentimes, I need to record my webcam and microphone, so I created a tiny snippet to automate this on my GNU/Linux system (ffmpeg devices are different in different operating systems as they depend on the kernel modules, one can do ffmpeg -devices to find the available devices on their system). One straight-up ffmpeg command to record webcam and microphone is:

ffmpeg -f pulse -i default -ac 2 -f video4linux2 -framerate 60 -video_size 1920x1080 -input_format mjpeg -i /dev/video0 <recording_file_name>

Here /dev/video0 is my webcam. Picking the right webcam device is sometimes tricky in Linux; I've written a tiny snippet on how to get the actual webcam device easily.

One might/would need to change the ffmpeg arguments to meet their need or as required by their system (man ffmpeg).

If we only need the microphone audio, we can only use the audio-grabbing portion of the ffmpeg command:

ffmpeg -f pulse -i default -ac 2 <recording_audio_file_name>

Similarly, if we only want the video from the webcam without any microphone audio:

ffmpeg -f video4linux2 -framerate 60 -video_size 1920x1080 -input_format mjpeg -i /dev/video0 <recording_video_file_name>

We can take this one step further by creating a shell function to invoke the ffmpeg command easily and also potentially with a generated filename on each invocation; I have the following in my shell's init file (tested on zsh and bash):

webcam_record () {
    # Can be called with an output filename, otherwise one will be created based on the current datetime
    out_file="$1"

    if [[ -z $out_file ]]; then
        out_dir="${HOME}/Videos/webcam"
        mkdir -p "$out_dir"
        out_file="${out_dir}/$(date '+%Y-%m-%dT%H:%M:%S').mkv"
        printf 'No output file given, capture will be saved to `%s`\n' "${out_file}"
    fi

    ffmpeg -f pulse -i default -ac 2 -f video4linux2 -framerate 60 -video_size 1920x1080 -input_format mjpeg -i /dev/video0 "${out_file}"
}

We can invoke it as webcam_record <filename> to save the output recording as <filename>. We can also invoke it as the bare function name webcam_record to have the output saved as an auto-generated filename (based on the invocation datetime, in the ISO-8601 format e.g. 2024-01-19T21:17:10.mkv) in the ${HOME}/Videos/webcam/ directory.

Comments

Comments powered by Disqus