controller_widget_builder.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import 'dart:async';
  2. import 'package:flutter/cupertino.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter_ijkplayer/flutter_ijkplayer.dart';
  5. import 'package:flutter_ijkplayer/src/helper/time_helper.dart';
  6. import 'package:flutter_ijkplayer/src/helper/logutil.dart';
  7. import 'package:flutter_ijkplayer/src/widget/progress_bar.dart';
  8. /// Using mediaController to Construct a Controller UI
  9. typedef Widget ControllerWidgetBuilder(IjkMediaController controller);
  10. /// default create IJK Controller UI
  11. Widget defaultBuildIjkControllerWidget(IjkMediaController controller) {
  12. return DefaultControllerWidget(
  13. controller: controller,
  14. // verticalGesture: false,
  15. // horizontalGesture: false,
  16. );
  17. }
  18. /// Default Controller Widget
  19. ///
  20. /// see [IjkPlayer] and [ControllerWidgetBuilder]
  21. class DefaultControllerWidget extends StatefulWidget {
  22. final IjkMediaController controller;
  23. /// If [doubleTapPlay] is true, can double tap to play or pause media.
  24. final bool doubleTapPlay;
  25. /// If [verticalGesture] is false, vertical gesture will be ignored.
  26. final bool verticalGesture;
  27. /// If [horizontalGesture] is false, horizontal gesture will be ignored.
  28. final bool horizontalGesture;
  29. /// Controlling [verticalGesture] is controlling system volume or media volume.
  30. final VolumeType volumeType;
  31. final bool playWillPauseOther;
  32. /// The UI of the controller.
  33. const DefaultControllerWidget({
  34. @required this.controller,
  35. this.doubleTapPlay = false,
  36. this.verticalGesture = true,
  37. this.horizontalGesture = true,
  38. this.volumeType = VolumeType.system,
  39. this.playWillPauseOther = true,
  40. });
  41. @override
  42. _DefaultControllerWidgetState createState() =>
  43. _DefaultControllerWidgetState();
  44. }
  45. class _DefaultControllerWidgetState extends State<DefaultControllerWidget>
  46. implements TooltipDelegate {
  47. IjkMediaController get controller => widget.controller;
  48. bool _isShow = true;
  49. set isShow(bool value) {
  50. _isShow = value;
  51. setState(() {});
  52. if (value == true) {
  53. controller.refreshVideoInfo();
  54. }
  55. }
  56. bool get isShow => _isShow;
  57. Timer progressTimer;
  58. StreamSubscription controllerSubscription;
  59. @override
  60. void initState() {
  61. super.initState();
  62. startTimer();
  63. controllerSubscription =
  64. controller.textureIdStream.listen(_onTextureIdChange);
  65. }
  66. void _onTextureIdChange(int textureId) {
  67. LogUtils.debug("onTextureChange $textureId");
  68. if (textureId != null) {
  69. startTimer();
  70. } else {
  71. stopTimer();
  72. }
  73. }
  74. @override
  75. void deactivate() {
  76. super.deactivate();
  77. }
  78. @override
  79. void dispose() {
  80. controllerSubscription.cancel();
  81. stopTimer();
  82. super.dispose();
  83. }
  84. void startTimer() {
  85. if (controller.textureId == null) {
  86. return;
  87. }
  88. progressTimer?.cancel();
  89. progressTimer = Timer.periodic(Duration(milliseconds: 400), (timer) {
  90. LogUtils.verbose("timer will call refresh info");
  91. controller.refreshVideoInfo();
  92. });
  93. }
  94. void stopTimer() {
  95. progressTimer?.cancel();
  96. }
  97. @override
  98. Widget build(BuildContext context) {
  99. return GestureDetector(
  100. behavior: HitTestBehavior.opaque,
  101. child: buildContent(),
  102. onDoubleTap: onDoubleTap(),
  103. onHorizontalDragStart: wrapHorizontalGesture(_onHorizontalDragStart),
  104. onHorizontalDragUpdate: wrapHorizontalGesture(_onHorizontalDragUpdate),
  105. onHorizontalDragEnd: wrapHorizontalGesture(_onHorizontalDragEnd),
  106. onVerticalDragStart: wrapVerticalGesture(_onVerticalDragStart),
  107. onVerticalDragUpdate: wrapVerticalGesture(_onVerticalDragUpdate),
  108. onVerticalDragEnd: wrapVerticalGesture(_onVerticalDragEnd),
  109. onTap: onTap,
  110. );
  111. }
  112. Widget buildContent() {
  113. if (!isShow) {
  114. return Container();
  115. }
  116. return StreamBuilder<VideoInfo>(
  117. stream: controller.videoInfoStream,
  118. builder: (context, snapshot) {
  119. var info = snapshot.data;
  120. if (info == null || !info.hasData) {
  121. return Container();
  122. }
  123. return buildPortrait(info);
  124. },
  125. );
  126. }
  127. Widget buildPortrait(VideoInfo info) {
  128. return PortraitController(
  129. controller: controller,
  130. info: info,
  131. tooltipDelegate: this,
  132. playWillPauseOther: widget.playWillPauseOther,
  133. );
  134. }
  135. OverlayEntry _tipOverlay;
  136. Widget createTooltipWidgetWrapper(Widget widget) {
  137. var typography = Typography(platform: TargetPlatform.android);
  138. var theme = typography.white;
  139. const style = const TextStyle(
  140. fontSize: 15.0,
  141. color: Colors.white,
  142. fontWeight: FontWeight.normal,
  143. );
  144. var mergedTextStyle = theme.body2.merge(style);
  145. return Container(
  146. decoration: BoxDecoration(
  147. color: Colors.black.withOpacity(0.5),
  148. borderRadius: BorderRadius.circular(20.0),
  149. ),
  150. height: 100.0,
  151. width: 100.0,
  152. child: DefaultTextStyle(
  153. child: widget,
  154. style: mergedTextStyle,
  155. ),
  156. );
  157. }
  158. void showTooltip(Widget widget) {
  159. hideTooltip();
  160. _tipOverlay = OverlayEntry(
  161. builder: (BuildContext context) {
  162. return IgnorePointer(
  163. child: Center(
  164. child: widget,
  165. ),
  166. );
  167. },
  168. );
  169. Overlay.of(context).insert(_tipOverlay);
  170. }
  171. void hideTooltip() {
  172. _tipOverlay?.remove();
  173. _tipOverlay = null;
  174. }
  175. _ProgressCalculator _calculator;
  176. onTap() => isShow = !isShow;
  177. Function onDoubleTap() {
  178. return widget.doubleTapPlay
  179. ? () {
  180. LogUtils.debug("ondouble tap");
  181. controller.playOrPause();
  182. }
  183. : null;
  184. }
  185. Function wrapHorizontalGesture(Function function) =>
  186. widget.horizontalGesture == true ? function : null;
  187. Function wrapVerticalGesture(Function function) =>
  188. widget.verticalGesture == true ? function : null;
  189. void _onHorizontalDragStart(DragStartDetails details) async {
  190. var videoInfo = await controller.getVideoInfo();
  191. _calculator = _ProgressCalculator(details, videoInfo);
  192. }
  193. void _onHorizontalDragUpdate(DragUpdateDetails details) {
  194. if (_calculator == null || details == null) {
  195. return;
  196. }
  197. var updateText = _calculator.calcUpdate(details);
  198. var offsetPosition = _calculator.getOffsetPosition();
  199. IconData iconData =
  200. offsetPosition > 0 ? Icons.fast_forward : Icons.fast_rewind;
  201. var w = Column(
  202. mainAxisAlignment: MainAxisAlignment.center,
  203. children: <Widget>[
  204. Icon(
  205. iconData,
  206. color: Colors.white,
  207. size: 40.0,
  208. ),
  209. Text(
  210. updateText,
  211. textAlign: TextAlign.center,
  212. ),
  213. ],
  214. );
  215. showTooltip(createTooltipWidgetWrapper(w));
  216. }
  217. void _onHorizontalDragEnd(DragEndDetails details) async {
  218. hideTooltip();
  219. var targetSeek = _calculator.getTargetSeek(details);
  220. _calculator = null;
  221. await controller.seekTo(targetSeek);
  222. var videoInfo = await controller.getVideoInfo();
  223. if (targetSeek < videoInfo.duration) await controller.play();
  224. }
  225. bool verticalDraging = false;
  226. void _onVerticalDragStart(DragStartDetails details) {
  227. print("drag start dx = ${details.globalPosition.dx}");
  228. verticalDraging = true;
  229. }
  230. void _onVerticalDragUpdate(DragUpdateDetails details) async {
  231. if (verticalDraging == false) return;
  232. if (details.delta.dy > 0) {
  233. await volumeDown();
  234. } else if (details.delta.dy < 0) {
  235. await volumeUp();
  236. }
  237. var currentVolume = await getVolume();
  238. var column = Column(
  239. mainAxisAlignment: MainAxisAlignment.center,
  240. children: <Widget>[
  241. Icon(
  242. Icons.volume_up,
  243. color: Colors.white,
  244. size: 25.0,
  245. ),
  246. Padding(
  247. padding: const EdgeInsets.only(top: 10.0),
  248. child: Text(currentVolume.toString()),
  249. ),
  250. ],
  251. );
  252. showTooltip(createTooltipWidgetWrapper(column));
  253. }
  254. void _onVerticalDragEnd(DragEndDetails details) async {
  255. verticalDraging = false;
  256. hideTooltip();
  257. Future.delayed(const Duration(milliseconds: 2000), () {
  258. hideTooltip();
  259. controller.hideSystemVolumeBar();
  260. });
  261. }
  262. Future<int> getVolume() async {
  263. switch (widget.volumeType) {
  264. case VolumeType.media:
  265. return controller.volume;
  266. case VolumeType.system:
  267. return controller.getSystemVolume();
  268. }
  269. return 0;
  270. }
  271. Future<void> volumeUp() async {
  272. var volume = await getVolume();
  273. volume++;
  274. switch (widget.volumeType) {
  275. case VolumeType.media:
  276. controller.volume = volume;
  277. break;
  278. case VolumeType.system:
  279. await IjkManager.systemVolumeUp();
  280. break;
  281. }
  282. }
  283. Future<void> volumeDown() async {
  284. var volume = await getVolume();
  285. volume--;
  286. switch (widget.volumeType) {
  287. case VolumeType.media:
  288. controller.volume = volume;
  289. break;
  290. case VolumeType.system:
  291. await IjkManager.systemVolumeDown();
  292. break;
  293. }
  294. }
  295. }
  296. class _ProgressCalculator {
  297. DragStartDetails startDetails;
  298. VideoInfo info;
  299. double dx;
  300. _ProgressCalculator(this.startDetails, this.info);
  301. String calcUpdate(DragUpdateDetails details) {
  302. dx = details.globalPosition.dx - startDetails.globalPosition.dx;
  303. var f = dx > 0 ? "+" : "-";
  304. var offset = getOffsetPosition().round().abs();
  305. return "$f${offset}s";
  306. }
  307. double getTargetSeek(DragEndDetails details) {
  308. var target = info.currentPosition + getOffsetPosition();
  309. if (target < 0) {
  310. target = 0;
  311. } else if (target > info.duration) {
  312. target = info.duration;
  313. }
  314. return target;
  315. }
  316. double getOffsetPosition() {
  317. return dx / 10;
  318. }
  319. }
  320. class PortraitController extends StatelessWidget {
  321. final IjkMediaController controller;
  322. final VideoInfo info;
  323. final TooltipDelegate tooltipDelegate;
  324. final bool playWillPauseOther;
  325. const PortraitController({
  326. Key key,
  327. this.controller,
  328. this.info,
  329. this.tooltipDelegate,
  330. this.playWillPauseOther = true,
  331. }) : super(key: key);
  332. bool get haveTime {
  333. return info.hasData && info.duration > 0;
  334. }
  335. @override
  336. Widget build(BuildContext context) {
  337. if (!info.hasData) {
  338. return Container();
  339. }
  340. Widget bottomBar = buildBottomBar(context);
  341. return Column(
  342. children: <Widget>[
  343. Expanded(
  344. child: Container(),
  345. ),
  346. bottomBar,
  347. ],
  348. );
  349. }
  350. Widget buildBottomBar(BuildContext context) {
  351. var currentTime = buildCurrentText();
  352. var maxTime = buildMaxTimeText();
  353. var progress = buildProgress(info);
  354. var playButton = buildPlayButton(context);
  355. Widget widget = Row(
  356. children: <Widget>[
  357. playButton,
  358. Padding(
  359. padding: const EdgeInsets.all(8.0),
  360. child: currentTime,
  361. ),
  362. Expanded(child: progress),
  363. Padding(
  364. padding: const EdgeInsets.all(8.0),
  365. child: maxTime,
  366. ),
  367. ],
  368. );
  369. widget = DefaultTextStyle(
  370. style: const TextStyle(
  371. color: Colors.white,
  372. ),
  373. child: widget,
  374. );
  375. widget = Container(
  376. color: Colors.black.withOpacity(0.12),
  377. child: widget,
  378. );
  379. return widget;
  380. }
  381. Widget buildProgress(VideoInfo info) {
  382. if (!info.hasData || info.duration == 0) {
  383. return Container();
  384. }
  385. return Container(
  386. height: 22,
  387. child: ProgressBar(
  388. current: info.currentPosition,
  389. max: info.duration,
  390. changeProgressHandler: (progress) async {
  391. await controller.seekToProgress(progress);
  392. tooltipDelegate?.hideTooltip();
  393. },
  394. tapProgressHandler: (progress) {
  395. showProgressTooltip(info, progress);
  396. },
  397. ),
  398. );
  399. }
  400. buildCurrentText() {
  401. return haveTime
  402. ? Text(
  403. TimeHelper.getTimeText(info.currentPosition),
  404. )
  405. : Container();
  406. }
  407. buildMaxTimeText() {
  408. return haveTime
  409. ? Text(
  410. TimeHelper.getTimeText(info.duration),
  411. )
  412. : Container();
  413. }
  414. buildPlayButton(BuildContext context) {
  415. return IconButton(
  416. onPressed: () {
  417. controller.playOrPause(pauseOther: playWillPauseOther);
  418. },
  419. color: Colors.white,
  420. icon: Icon(info.isPlaying ? Icons.pause : Icons.play_arrow),
  421. iconSize: 25.0,
  422. );
  423. }
  424. void showProgressTooltip(VideoInfo info, double progress) {
  425. var target = info.duration * progress;
  426. var diff = info.currentPosition - target;
  427. String diffString;
  428. if (diff < 1 && diff > -1) {
  429. diffString = "0s";
  430. } else if (diff < 0) {
  431. diffString = "+${TimeHelper.getTimeText(diff.abs())}";
  432. } else if (diff > 0) {
  433. diffString = "-${TimeHelper.getTimeText(diff.abs())}";
  434. } else {
  435. diffString = "0s";
  436. }
  437. Widget text = Container(
  438. alignment: Alignment.center,
  439. child: Column(
  440. mainAxisAlignment: MainAxisAlignment.center,
  441. children: <Widget>[
  442. Text(
  443. TimeHelper.getTimeText(target),
  444. style: TextStyle(fontSize: 20),
  445. ),
  446. Container(
  447. height: 10,
  448. ),
  449. Text(diffString),
  450. ],
  451. ),
  452. );
  453. var tooltip = tooltipDelegate?.createTooltipWidgetWrapper(text);
  454. tooltipDelegate?.showTooltip(tooltip);
  455. }
  456. }
  457. abstract class TooltipDelegate {
  458. void showTooltip(Widget widget);
  459. Widget createTooltipWidgetWrapper(Widget widget);
  460. void hideTooltip();
  461. }
  462. enum VolumeType {
  463. system,
  464. media,
  465. }