Automatically take 8 screenshots of a video using mplayer

By xngo on February 24, 2019

#!/bin/bash
# Description: Automatically take 8 screenshots of a video using mplayer
#              Screenshots are saved in 01.png, 02.png, ..., 08.png
# Usage: ./thisScript.sh VideoFilename
# Requirements: mplayer, grep, sed
 
filename="$1"
 
# For some unknown reason, the last screenshot is not generated by mplayer.
# Therefore, always add 1 more to the total number of screenshots that you want.
NUM_OF_SCREENSHOTS=9
 
# Get the total length of the video in seconds.
#  Use mplayer to display the info of the video and then get the value of ID_LENGTH, the total number of seconds of the video.
total_length=$(mplayer -identify -frames 0 -vc null -vo null -ao null ${filename} | grep ID_LENGTH | sed 's/ID_LENGTH=//' | sed 's/\..*//')
 
# Remove 4 seconds from the video so that it doesn't take screenshot at the ends.
let total_length-=4
 
# time_slice: At which time interval should mplayer take screenshots.
let time_slice=${total_length}/${NUM_OF_SCREENSHOTS}
 
# time_at: When should mplayer take screenshots.
time_at=${time_slice};
 
# Looping to take screenshots.
for ((i=1; i <= NUM_OF_SCREENSHOTS ; i++))
do
 
  # Create unique filename.
  padding=$(printf %03d ${i})
 
  # Take the screenshot.
  mplayer -nosound -ss ${time_at} -vf screenshot -frames 1 -vo png:z=9 ${filename}
 
  # Increment to the next time slice.
  let time_at+=${time_slice}
 
  # Move the screenshot 00000001.png to 0X.png
  mv 00000001.png ${padding}.png
 
done

References

  • http://wiki.awkwardtv.org/wiki/Create_Cover-Preview_from_Moviefile_Screenshot
  • http://lists.mplayerhq.hu/pipermail/mplayer-users/2009-October/077955.html
  • http://forums.animesuki.com/archive/index.php/t-1335.html
  • http://www.perlmonks.org/?node_id=659150
  • http://p.outlyer.net/vcs/

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.