python+adb实现截屏/录屏功能

当测试一些物联网产品使用安卓系统,但系统界面没有像手机那么方便操作时,可以考虑使用adb命令实现对测试产品的截屏/录屏,adb shell screenrecord可以实现对安卓系统的录屏功能,截屏则使用screencap命令。查看帮助命令,参数 --help

adb shell screenrecord --help

参数说明:

  1. 开始录制命令:

adb shell screenrecord /sdcard/demo.mp4

说明:录制手机屏幕,视频格式为mp4,存放到手机sd卡里,默认录制时间为180s。

screenrecord是一个shell命令,支持Android4.4(API level 19)以上,支持视频格式: mp4

2. 指定视频分辨率大小,参数 --size

adb shell screenrecord --size 1280*720 /sdcard/demo.mp4

说明:录制视频,分辨率为1280*720,如果不指定默认使用手机的分辨率,为获得最佳效果,请使用设备上的高级视频编码(AVC)支持的大小

3. 指定视频的比特率, 参数 --bit-rate

adb shell screenrecord --bit-rate 6000000 /sdcard/demo.mp4

扫描二维码关注公众号,回复: 14888475 查看本文章

说明:指定视频的比特率为6Mbps,如果不指定,默认为4Mbps. 你可以增加比特率以提高视频质量或为了让文件更小而降低比特率

4. 旋转90度,参数: --rotate

adb shell screenrecord --rotate /sdcard/demo.mp4

说明:此功能为实验性的,在nexus6设备上实验,录制的视频播放时也是旋转90度播放,体验不太友好。

5. 导出视频:

adb pull /sdcard/demo.mp4 D:/

说明:导出视频的位置在D盘根目录下,名称为demo.mp4

也可以结合python实现代码如下:

import os
import datetime
import subprocess


class ADB:
    def __init__(self, device, target_path):
        self.target_path = target_path
        subprocess.Popen(f"adb connect {device}")   # adb连接安卓设备

    def screenshot(self):
        # 使用 && 隔开。
        file_name = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
        step1 = rf"cd {self.target_path}"
        step2 = f"adb shell screencap /sdcard/{file_name}.png"
        step3 = f"adb pull sdcard/{file_name}.png ./"   # 将截屏图片传到电脑设备
        command = fr"{step1} && {step2} && {step3}"
        os.popen(command)

    def video(self, record_time):   # 录制时间单位为秒
        # 采集
        file_name = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        step1 = rf"cd {self.target_path}"
        step2 = f"adb shell screenrecord  --time-limit {record_time} /sdcard/{file_name}.mp4"
        command = fr"{step1} && {step2}"
        os.system(command)

        # 拉取录屏文件到电脑设备
        step4 = rf"adb pull sdcard/{file_name}.mp4 ./"
        command2 = fr"{step1} && {step4}"
        os.system(command2)


if __name__ == '__main__':
    deviceIp = "10.32.3.51"
    target_path = r"C:\Users\DM\Desktop\录屏视频"
    adb = ADB(deviceIp, target_path)
    # adb.screenshot()
    adb.video(60)

猜你喜欢

转载自blog.csdn.net/qq_38571773/article/details/128817480