实例介绍
【实例简介】C# 手机使用USB投屏电脑(只适用Android)
将手机打开“开发人员模式”,然后“允许USB调试”,链接电脑,此过程不会的百度查。
原理:调用adb命令控制手机录屏,输出到一个播放器。
画面流畅不卡。
adb不知道的百度查询。
adb相关操作参考:
https://github.com/TGSAN/MirrorCaster
播放器参考:
https://github.com/mpv-player/mpv
以上均为开源软件,全部源代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | using System; using System.Diagnostics; using System.IO.Pipes; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace Phone_Demo { public partial class Form1 : Form { public class DeviceInfoData { public int deviceWidth = 1920; public int deviceHeight = 1080; public double deviceRefreshRate = 60; public bool deviceVmode = false ; } private Process stdoutProcess = null ; private Process stdinProcess = null ; private StreamPipe rePipe; private readonly DeviceInfoData deviceInfoData = new DeviceInfoData(); private readonly DeviceInfoData instartDeviceInfoData = new DeviceInfoData(); private double castMbitRate = 30; public Form1() { InitializeComponent(); this .FormClosed = (s, e) => { Kill_Process( "adb" ); }; } private void button1_Click( object sender, EventArgs e) { StopCast(); if (UpdateScreenDeviceInfo()) { StartCast(); } } private void StartCast() { stdoutProcess = new Process(); stdinProcess = new Process(); StdOut(); StdIn(); rePipe = new StreamPipe(stdoutProcess.StandardOutput.BaseStream, stdinProcess.StandardInput.BaseStream); rePipe.Connect(); instartDeviceInfoData.deviceVmode = deviceInfoData.deviceVmode; // 记录播放时的横竖屏状态 } private void StopCast() { try { try { if (stdoutProcess != null ) { stdoutProcess.Exited -= StdIOProcess_Exited; stdoutProcess.Kill(); stdoutProcess = null ; } } catch (Exception ex) { MessageBox.Show( "无法关闭StdOUT," ex.Message); } try { if (stdinProcess != null ) { stdinProcess.Exited -= StdIOProcess_Exited; stdinProcess.Kill(); stdoutProcess = null ; } } catch (Exception ex) { MessageBox.Show( "无法关闭StdIN," ex.Message); } if (rePipe != null ) { rePipe.Disconnect(); } } catch (Exception ex) { MessageBox.Show( "无法断开重定向," ex.Message); } nosigalLabel.Text = "等一下...,滑动手机屏幕" ; } private string ADBResult( string args) { Process process = new Process(); process.StartInfo.FileName = System.AppDomain.CurrentDomain.BaseDirectory @"lib\adb\adb.exe" ; process.StartInfo.Arguments = args; process.StartInfo.UseShellExecute = false ; process.StartInfo.RedirectStandardOutput = true ; process.StartInfo.RedirectStandardError = true ; process.StartInfo.CreateNoWindow = true ; process.StartInfo.StandardOutputEncoding = Encoding.UTF8; process.Start(); string result = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadLine(); process.Close(); return error result; } private bool UpdateScreenDeviceInfo() { string str = ADBResult( "shell \"dumpsys window displays && dumpsys SurfaceFlinger\"" ).ToLower(); if (str.StartsWith( "error: no devices/emulators found" )) { MessageBox.Show( "找不到任何设备或模拟器" ); return false ; } else if (str.StartsWith( "error: more than one device/emulator" )) { MessageBox.Show( "暂时只支持单个设备开启 ADB 调试" ); return false ; } Regex regexSize = new Regex( @"\s cur=(?<width>[0-9]*)x(?<height>[0-9]*?)\s " , RegexOptions.Multiline); Match matchSize = regexSize.Match(str); Regex regexRefreshRate = new Regex( @"\s refresh-rate. ?(?<refreshRate>[0-9]*\.{0,1}[0-9]*?)\s*fps\s " , RegexOptions.Multiline); Match matchRefreshRate = regexRefreshRate.Match(str); if (matchSize.Success) { try { int width = int .Parse(matchSize.Groups[ "width" ].Value); //宽 int height = int .Parse(matchSize.Groups[ "height" ].Value); //高 bool vmode = true ; //垂直 if (width > height) { vmode = false ; //水平 } deviceInfoData.deviceWidth = width; deviceInfoData.deviceHeight = height; deviceInfoData.deviceVmode = vmode; } catch { } } if (matchRefreshRate.Success) { try { double refreshRate = double .Parse(matchRefreshRate.Groups[ "refreshRate" ].Value); deviceInfoData.deviceRefreshRate = refreshRate; } catch { } } return true ; } private void StdIOProcess_Exited( object sender, EventArgs e) { StopCast(); } /// adb 录屏控制 private void StdOut() { stdoutProcess.StartInfo.FileName = @"lib\adb\adb.exe" ; stdoutProcess.StartInfo.Arguments = $ "exec-out \"while true;do screenrecord --bit-rate={(int)(castMbitRate * 1000000)} --output-format=h264 --size {deviceInfoData.deviceWidth.ToString()}x{deviceInfoData.deviceHeight.ToString()} - ;done\"" ; // stdoutProcess.StartInfo.UseShellExecute = false ; stdoutProcess.StartInfo.RedirectStandardOutput = true ; stdoutProcess.StartInfo.CreateNoWindow = true ; stdoutProcess.EnableRaisingEvents = true ; stdoutProcess.Exited = StdIOProcess_Exited; stdoutProcess.Start(); if (stdinProcess.StartInfo.FileName.Length != 0) { stdinProcess.CancelOutputRead(); stdinProcess.Close(); } } /// 播放器控制 private void StdIn() { string widArg = $ "--wid={screenBox.Handle.ToInt64().ToString()}" ; string vsyncArgs = "--d3d11-sync-interval=" ( false ? "1" : "0" ); string releaseArgs = "--input-default-bindings=no --osd-level=0" ; string fpsControlArgs = false ? $ "--no-correct-pts --fps={deviceInfoData.deviceRefreshRate}" : "--untimed" ; string hwdecArgs = true ? "--hwdec=yes" : "--hwdec=no" ; string mpvFullArgs = $ "--title=\"Phone Demo\" --cache=no --no-cache --profile=low-latency --framedrop=decoder {vsyncArgs} --scale=spline36 --cscale=spline36 --dscale=mitchell --correct-downscaling=yes --linear-downscaling=yes --sigmoid-upscaling=yes {fpsControlArgs} --video-latency-hacks=yes --vo=gpu {hwdecArgs} --no-audio --no-config --no-border -no-osc --no-taskbar-progress {releaseArgs} {widArg} -" ; Console.WriteLine( "MPV ARGS:\r\n" mpvFullArgs); stdinProcess.StartInfo.FileName = @"lib\mpv\mpv.exe" ; stdinProcess.StartInfo.Arguments = mpvFullArgs; stdinProcess.StartInfo.UseShellExecute = false ; stdinProcess.StartInfo.RedirectStandardOutput = true ; stdinProcess.StartInfo.RedirectStandardInput = true ; stdinProcess.StartInfo.CreateNoWindow = true ; stdinProcess.EnableRaisingEvents = true ; stdinProcess.Exited = StdIOProcess_Exited; stdinProcess.Start(); stdinProcess.BeginOutputReadLine(); } /// 删除进程 private void Kill_Process( string processName) { foreach (Process p in Process.GetProcesses()) { if (p.ProcessName.Contains(processName)) { try { p.Kill(); p.WaitForExit(); } catch { } } } } } } |
【实例截图】
【核心代码】
.├── C# 手机使用USB投屏电脑(只适用Android).rar
└── Phone_Demo
├── Phone_Demo
│ ├── App.config
│ ├── Form1.Designer.cs
│ ├── Form1.cs
│ ├── Form1.resx
│ ├── Phone_Demo.csproj
│ ├── Program.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ ├── Resources.Designer.cs
│ │ ├── Resources.resx
│ │ ├── Settings.Designer.cs
│ │ └── Settings.settings
│ ├── StreamPipe.cs
│ ├── bin
│ │ └── Debug
│ │ ├── Phone_Demo.exe
│ │ ├── Phone_Demo.exe.config
│ │ ├── Phone_Demo.pdb
│ │ └── lib
│ │ ├── adb
│ │ │ ├── AdbWinApi.dll
│ │ │ ├── AdbWinUsbApi.dll
│ │ │ ├── adb.exe
│ │ │ └── libwinpthread-1.dll
│ │ └── mpv
│ │ ├── d3dcompiler_43.dll
│ │ └── mpv.exe
│ └── obj
│ └── Debug
└── Phone_Demo.sln
10 directories, 23 files
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论