Objective
Write a bash script that implements a line of commands to get an Android phone to record a GIF file on the screen.
Bloggers Use the Ubuntu system, and the shell is bash. This script can also be used on Mac systems.
I heard that the Windows system out of Ubuntu on Windows, do not know if you can use this script.
Principle adb shell Screenrecord
After Android 4.4, a screenrecord command was preset in the system that can be used to record the screen in MP4 format. The specific command format can be viewed through the Help parameter:
$ adb shell screenrecord --helpUsage: screenrecord [options] <filename>Android screenrecord v1.2. Records the device‘s display to a .mp4 file.Options:--size WIDTHxHEIGHT Set the video size, e.g. "1280x720". Default is the device‘s main display resolution (if supported), 1280x720 if not. For best results, use a size supported by the AVC encoder.--bit-rate RATE Set the video bit rate, in bits per second. Value may be specified as bits or megabits, e.g. ‘4000000‘ is equivalent to ‘4M‘. Default 4Mbps.--bugreport Add additional information, such as a timestamp overlay, that is helpful in videos captured to illustrate bugs.--time-limit TIME Set the maximum recording time, in seconds. Default / maximum is 180.--verbose Display interesting information on stdout.--help Show this message.Recording continues until Ctrl-C is hit or the time limit is reached.
Example:
adb shell screenrecord --size "360x640" --bit-rate 2000000 /sdcard/android_screenrecord_test.mp4
The above command will record the connected phone screen as a wide-height 360x640, bit rate 2M video, saved as the Android_screenrecord_test.mp4 file in the root directory of the phone SD card.
The command continues recording until the command is terminated with Ctrl-c, and the recording is ended.
You can also use the –time-limit time parameter to pre-specify the length of the recording, which will end automatically. The default maximum duration is 3 minutes.
Ffmpeg
Extract the video as a series of pictures using the FFmpeg draw frame command:
ffmpeg -i video.mp4 -r 5 ‘frames/frame-%03d.jpg‘
Where: -r 5 represents the extracted frame rate, that is, the video is extracted 5 frames per second.
Convert
Use the Convert command in the ImageMagick package to combine a series of pictures into a GIF motion format:
convert -delay 20 -loop 0 *.jpg myimage.gif
Where: -delay 20 represents the time interval between each frame of the generated GIF, which shows the next frame every 0.2 seconds.
If the convert command is not available within the system, you can install it with the following command:
sudo apt-get install imagemagick
Bloggers using Ubuntu 16.10, this command is preset in the system, do not need to install.
FFmpeg and convert parameter settings
The above two commands, ffmpeg -r 5 and convert -delay 20 the two parameter values, respectively, are the video extraction frame interval and gif per frame interval, assuming that they are video_fps and gif_delay respectively, then these two parameters must meet the following conditions when setting up:
video_fps * gif_delay = 100
If the product is less than 100, the resulting GIF will be faster than the original playback speed;
If the product is greater than 100, the resulting GIF will be slower than the original playback speed.
As for the reasons, combined with the introduction of these two parameters, think about it to understand.
Capturing the recording End event
The above three commands are called separately, the realization of the recording screen for GIF is quite simple.
If you want to write three commands in a script and complete the function in one process, the first thing to solve is how to capture the recording end event, the Ctrl-c command.
The following script can be implemented in bash:
# catch ctrl-c signalCTRL_C() { # ctrl-c hit, do something}trap CTRL_C SIGINT
With this method to get the recording end event, it's easy to go down.
A pit is encountered here, that is, if you start converting GIF directly after capturing ctrl-c, it will fail. After several attempts, the discovery is ctrl-c after actually Android's Screenrecord command did not finish, this time the video is not available. The solution is simple and rough, let the script sleep 2 seconds in situ, then to operate the generated MP4 file is available.
Final script
I don't know what to write, just post the complete script:
#!/bin/bash# Author: [Email protected]#========================================================# define Param group hereQuality_1= ("360x640" 1000000 4 -) quality_2= ("360x640" 1000000 5 -) quality_3= ("360x640" 1000000 Ten Ten) quality_4= ("720x1280" 1000000 4 -) quality_5= ("720x1280" 1000000 5 -)#========================================================Quality= (${quality_2[@]}) resolution=${quality[0]}Bit_rate=${quality[1]}gif_fps=${quality[2]}gif_delay=${quality[3]}# Gif_fps and Gif_delay must meet the following condition:# Gif_fps * Gif_delay =output_file_name=android_screen_record.$ (date +%m%d%h%m%s). gifoutput_file_dir=$ (pwd) output_video_name=screenrecord_$ (date +%m%d%h%m%s). mp4output_video_device_dir=/sdcardtmp_dir=/tmp/android_ screen_to_gif_$ (date +%m%d%h%m%s) recording=true# You could use adb by absolute file path. If so, specify it hereadb="adb"#========================================================# catch Ctrl-c signalCtrl_c() {if $RECORDING; Then Echo "Stop recording. Start convert ... "recording=false Else # Ctrl-c hit and not for stop recording, just exit. Exit$?fi # adb Screenrecord may still deal with MP4 file creating, # Just wait for it a little while.Sleep2s ADB pull$OUTPUT _video_device_dir/$OUTPUT _video_name $TMP _dir if[- F $TMP _dir/$OUTPUT _video_name]; Then # Remove video on phoneADB Shell RM$OUTPUT _video_device_dir/$OUTPUT _video_name Echo "Converting file: $TMP _dir/$OUTPUT _video_name"Mp4togif$TMP _dir/$OUTPUT _video_name Else Echo "* Create screen record mp4 fail" Exit 2 fi}trap Ctrl_c SIGINT# Catch Script Exit eventclear_work() {if[- e $TMP _dir]; Then # Since the TMP files have been put into/tmp/dir, they'll get # removed on system reboot. Thus we is in no hurry to remove them now. # Un-commit This line if you want to remove TMP files immediately after script run #rm $TMP _dir Echo fi}trap"Clear_work"EXIT#========================================================functionMp4togif() {Echo "* * * * EXTRACT Frames * * *"Mkdir$TMP _dir/frames Ffmpeg-i $-R$GIF _fps "$TMP _dir/frames/frame-%03d.jpg" Echo "* * * convert frames to GIF * * * *"Convert-delay$GIF _delay-loop0 "$TMP _dir/frames/*.jpg" $OUTPUT _file_dir/$OUTPUT _file_name}#========================================================if[ !- D "$OUTPUT _file_dir"]; Then Echo "* Output dir NOT exists: $OUTPUT _file_dir" Exit 1fiif[ !- e $TMP _dir]; ThenMkdir$TMP _dirfiif[ !- e $TMP _dir]; Then Echo "* tmp dir NOT exists: $TMP _dir" Exit 1fiEcho "params: $RESOLUTION, $BIT _rate, $GIF _fps, $GIF _delay"adb shell Screenrecord--verbose--size$RESOLUTION--bit-rate$BIT _rate $OUTPUT _video_device_dir/$OUTPUT _video_name
The several arrays defined at the beginning are for ease of testing. The resulting GIF file is also stored directly in the current directory.
Mainly because with the parameterization, the code will be much more, it is not easy to find the main function.
A complete script with parametric, easy-to-help documentation can be found in the following links:
android_screen2gif.sh
Use
Usage Prerequisites:
- The ADB can connect to the phone normally, but there is no such thing as offline. (Here Amway another article: addressing Ubuntu adb device identification issues)
- The phone must be over 4.4 systems.
The script itself is designed to use simple writing. You can start your phone screen recording by simply executing the script directly at the command line. Because it is a test, select the/tmp directory operation.
$ cd /tmp/$ android_screen2gif.sh params: 360x640, 1000000, 5, 20Main display is 720x1280 @60.00fps (orientation=0)Configuring recorder for 360x640 video/avc at 1.00MbpsContent area is 360x640 at offset x=0 y=0
At this point the recording is in progress and the command line hangs. When you think the recording can end, press ctrl-c, record the end, and start converting GIF steps. It usually takes 3-4 seconds for the screen GIF to be generated in the current directory.
^Cstop recording. start convert...[100%] /sdcard/screenrecord_0407090859.mp4converting file: /tmp/android_screen_to_gif_0407090859/screenrecord_0407090859.mp4*** extract frames ***ffmpeg version 3.0.7-0ubuntu0.16.10.1 Copyright (c) 2000-2017 the FFmpeg developers......Input #0, mov,mp4,m4a,3gp,3g2,mj2, from ‘/tmp/android_screen_to_gif_0407090859/screenrecord_0407090859.mp4‘:......Output #0, image2, to ‘/tmp/android_screen_to_gif_0407090859/frames/frame-%03d.jpg‘:......*** convert frames to gif ***result gif file:/tmp/android_screen_record.0407090859.gif
This step outputs more and ...... replaces some of the output. The last line is the final GIF recording screen file.
Parameter recommendations
According to the self-test and the process of final GIF generation, the following conclusions can be obtained:
Video resolution Parameters:
The larger the wider the greater the clearer, the larger the resulting GIF file. This is very obvious.
It is best to set the resolution to a scale of 9:16 according to the vertical display of the phone. If you set it to a different scale, such as 480:480, the recorded video will have a wide black edge.
video bit rate parameters:
First of all, the bit rate setting basically does not affect the quality of the resulting GIF file.
Because the final GIF file from the video frame, the size of the video bitrate for example, 10 frames per second, such as the need to extract the image clarity has little effect. Therefore, in order to reduce the intermediate file, it is recommended to set this parameter low.
Frame rate and interval per frame:
These two parameters have a significant impact on the final GIF quality. which
The larger the frame rate, the higher the quality of the GIF.
The smaller each frame interval, the higher the final GIF quality.
As mentioned above, these two parameters must be set in pairs. If both parameters are integers, you can basically set the following pairs:
2, 504, 255, 2010, 10
which
10, 10This group, set to 10 frames per second, gif every frame interval of 0.1 seconds, so that the 5-second GIF file will be about 10M size.
2, 50This group, set 2 frames per second, gif every frame interval of 0.5 seconds, the final GIF file is very serious.
Therefore 5, 20 , it is recommended to select this set of parameters. If the GIF quality requirements are high, you can try 10, 10 this set of parameters.
In summary, the small partners can try to set different combinations of parameters, try to experience how to set a few times.
Reference:
Create GIF from MP4 via command line
Command Convert doc
Once again the shameless Amway own script project:
android_screen2gif.sh
One-click Script to generate Android screen gif