image.png
因為一直需要將手機上的效果錄制下來,轉成gif,然后上傳到博客上。
原來都需要手動操作好幾次,所以索性的寫了一個腳本來配合使用。
環境準備腳本書寫關鍵的幾個指令
0.adb截屏
adb shell screencap -p /sdcard/screencap.png
adb錄屏
--time-limit 參數是限定時間的長短
F:\AndroidSDK\platform-tools\adb shell screenrecord --time-limit %t% /sdcard/demo.mp4
pull到電腦上
F:\AndroidSDK\platform-tools\adb pull /sdcard/demo.mp4
命令轉成gif
F:\ffmpeg-20171128-86cead5-win64-static\ffmpeg-20171128-86cead5-win64-static\bin/ffmpeg -i demo.mp4 -s 360x640 -r 10 target-%dh%.gif

ffmpeg -i 視頻源地址 -strict -2 -vf crop=1080:1080:0:420 視頻輸出地址(如:out.mp4)
其中的 crop=1080:1080:0:420 才裁剪參數,具體含義是,其中 width 和 表示裁剪后的尺寸,x:y 表示裁剪區域的左上角坐標。比如當前這個示例屏幕錄制gif工具,我們只需要保留豎向視頻的中間部分,所以 x 不用偏移,故傳入0屏幕錄制gif工具,而 y 則需要向下偏移:(1920 – 1080) / 2 = 420
完整的腳本
@echo off
set /p t=請輸入錄制時間s:
rem 開始錄制
adb shell screenrecord --time-limit %t% /sdcard/demo.mp4
adb pull /sdcard/demo.mp4
set h=%date:~0,4%%date:~5,2%%date:~8,2%%time:~0,2%%time:~3,2%%time:~6,2%
set dh=%h: =0%
rem ffmpeg轉換
F:\ffmpeg-20171128-86cead5-win64-static\ffmpeg-20171128-86cead5-win64-static\bin/ffmpeg -i demo.mp4 -s 360x640 -r 10 target-%dh%.gif
rem 刪除緩存的視頻
del demo.mp4

rem 直接打開我們最后的gif
start target-%dh%.gif
@Echo off&setlocal,EnableDelayedExpansion
set /p duration=請輸入錄制時間(秒):
set h=%date:~0,4%%date:~5,2%%date:~8,2%%time:~0,2%%time:~3,2%%time:~6,2%
set dh=%h: =0%
:isCrop
set /p isCrop=是否需要裁剪(y/n):
IF /i "!isCrop!"=="Y" (
set /p cropHeight= 輸入裁剪的高度:
rem /a表示進行數值運算
set /A convertHeight=!cropHeight!/3
Echo !convertHeight! , cropHeight =!cropHeight!

Echo 開始錄制
adb shell screenrecord --time-limit %duration% /sdcard/demo.mp4
adb pull /sdcard/demo.mp4
Echo ffmpeg轉換
F:\ffmpeg-20171128-86cead5-win64-static\ffmpeg-20171128-86cead5-win64-static\bin/ffmpeg -i demo.mp4 -vf crop=1080:!cropHeight!:0:0 -s 360x!convertHeight! -r 10 target-%dh%.gif
)else (
Echo 開始錄制
adb shell screenrecord --time-limit %duration% /sdcard/demo.mp4
adb pull /sdcard/demo.mp4
Echo ffmpeg轉換
F:\ffmpeg-20171128-86cead5-win64-static\ffmpeg-20171128-86cead5-win64-static\bin/ffmpeg -i demo.mp4 -s 360x640 -r 10 target-%dh%.gif
)
Echo 刪除緩存的視頻
del demo.mp4
Echo 直接打開我們最后的gif

start target-%dh%.gif
@Echo off
set h=%date:~0,4%%date:~5,2%%date:~8,2%%time:~0,2%%time:~3,2%%time:~6,2%
set dh=%h: =0%
echo 正在截屏
adb shell screencap -p /sdcard/screencap.png
adb pull /sdcard/screencap.png
ren screencap.png screencap-%dh%.png
echo 完成關閉
最后主要注意編碼問題,請選擇腳本的編碼為GBK。以免出現中文亂碼的問題
保存成.bat文件,這樣雙擊就能運行,然后就可以愉快的得到gif了。
Linux/Mac
#!/bin/bash
echo -e '請輸入錄制時間:'

read t
echo -e '開始錄制'
adb shell screenrecord --time-limit $t /sdcard/demo.mp4
adb pull /sdcard/demo.mp4
# # 獲取時間戳
currentTimeStamp=$(date +%s)
echo $currentTimeStamp
#'ffmpeg轉換'
ffmpeg -i demo.mp4 -s 360x640 -r 10 target-$currentTimeStamp.gif
#'刪除緩存的視頻'
rm -f demo.mp4
# '輸出打開我們最后的gif /r'
echo "$(cd `dirname $0`; pwd)"/target-$currentTimeStamp.gif
注意需要給腳本對應的權限。
保存成.sh文件,就可以運行,最后輸出的就是文件所在的路徑。