大家在做Android自动化测试时,如果用例报错了是不是都想要重现这个错误,除了代码日志、截图的回放,还有更为准确的是录制屏幕的回放。所以拉法今天就给大家介绍一下自己在实践中用过的录屏方法。
可以关注小编wx公众号“智测PLUS”,有更多好文章噢!
一、ADB的方式
adb命令录制屏幕
adb shell screenrecord /sdcard/demo.mp4
该命令会在设备的/sdcard目录下录制视频,并保存为demo.mp4文件。视频录制时长默认为180秒(3分钟),可以通过添加参数--time-limit来指定录制时长,单位为秒,例如:
adb shell screenrecord /sdcard/demo.mp4 --time-limit 60
停止录制
adb shell am broadcast -a com.android.server.scrcmd.stoprecord
设置视频分辨率
adb shell screenrecord /sdcard/demo.mp4 --size 640x480
设置视频比特率
adb shell screenrecord /sdcard/demo.mp4 --bit-rate 4000000
设置视频保持的时长(秒)
adb shell screenrecord /sdcard/demo.mp4 --time-limit 30
使用麦克风录制音频
adb shell screenrecord /sdcard/demo.mp4 --mic
使用系统音频录制音频
adb shell screenrecord /sdcard/demo.mp4 --external-audio
注意:很多品牌已经把这个权限回收了,不一定都能用(比如华为)
二、Scrcpy的方式
Scrcpy是一个开源免费的软件,它可以录制视频也可以投屏。我们着重讲他如何录制视频。
源码:https://github.com/Genymobile/scrcpy
安装
windows:https://github.com/Genymobile/scrcpy/blob/master/doc/windows.md
mac: https://github.com/Genymobile/scrcpy/blob/master/doc/macos.md
录制视频的命令
scrcpy -s {deviceid} --no-playback --record=demo.mkv
python代码
class Scrcpy:
# 此处只放了windows平台的scrcpy的程序地址,mac自定安装配好环境变量即可
STATICPATH = os.path.dirname(os.path.realpath(__file__))
DEFAULT_SCRCPY_PATH = {
"64": os.path.join(STATICPATH, "scrcpy", "scrcpy-win64-v2.1.1", "scrcpy.exe"),
"32": os.path.join(STATICPATH, "scrcpy", "scrcpy-win32-v2.1.1", "scrcpy.exe"),
"default":"scrcpy"
}
@classmethod
def scrcpy_path(cls):
bit = platform.architecture()[0]
path = cls.DEFAULT_SCRCPY_PATH["default"]
if platform.system().lower().__contains__('windows'):
if bit.__contains__('64'):
path = cls.DEFAULT_SCRCPY_PATH["64"]
elif bit.__contains__('32'):
path = cls.DEFAULT_SCRCPY_PATH["32"]
return path
@classmethod
def start_record(cls, device):
f = File()
logger.info('start record screen')
win_cmd = "start /b {scrcpy_path} -s {deviceId} --no-playback --record={video}".format(
scrcpy_path = cls.scrcpy_path(),
deviceId = device,
video = os.path.join(f.report_dir, 'record.mkv')
)
mac_cmd = "nohup {scrcpy_path} -s {deviceId} --no-playback --record={video} &".format(
scrcpy_path = cls.scrcpy_path(),
deviceId = device,
video = os.path.join(f.report_dir, 'record.mkv')
)
if platform.system().lower().__contains__('windows'):
result = os.system(win_cmd)
else:
result = os.system(mac_cmd)
if result == 0:
logger.info("record screen success : {}".format(os.path.join(f.report_dir, 'record.mkv')))
else:
logger.info("Please install the software yourself : brew install scrcpy")
return result
@classmethod
def stop_record(cls):
logger.info('stop scrcpy process')
pids = psutil.pids()
try:
for pid in pids:
p = psutil.Process(pid)
if p.name().__contains__('scrcpy'):
os.kill(pid, signal.SIGABRT)
logger.info(pid)
except Exception as e:
logger.exception(e)