poem_record_video.dart
17.5 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import 'dart:async';
import 'dart:io';
import 'package:Parlando/net/dio_utils.dart';
import 'package:Parlando/net/http_api.dart';
import 'package:Parlando/poem/models/poem_entity.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:Parlando/res/resources.dart';
import 'package:Parlando/routers/fluro_navigator.dart';
import 'package:Parlando/util/toast_utils.dart';
import 'package:Parlando/widgets/my_app_bar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pausable_timer/pausable_timer.dart';
import 'package:video_player/video_player.dart';
import 'package:Parlando/extension/int_extension.dart';
import 'package:wakelock/wakelock.dart';
import '../poem_router.dart';
class PoemRecordVideoPage extends StatefulWidget {
final int id;
final int poemId;
final int type;
const PoemRecordVideoPage({
Key? key,
required this.id,
required this.type,
required this.poemId,
}) : super(key: key);
@override
PoemRecordVideoPageState createState() => PoemRecordVideoPageState();
}
class PoemRecordVideoPageState extends State<PoemRecordVideoPage>
with WidgetsBindingObserver {
CameraController? controller;
VideoPlayerController? videoController;
File? _videoFile; // 保存的视频文件位置,用于上传视频的时候用!
PoemData? _poem;
final bool _isVideoCameraSelected = true;
bool _isCameraInitialized = false;
bool _isRearCameraSelected = true;
bool _isRecordingInProgress = false;
List<File> allFileList = [];
final resolutionPresets = ResolutionPreset.values;
ResolutionPreset currentResolutionPreset = ResolutionPreset.high;
List<CameraDescription>? cameras = [];
late final PausableTimer _timer;
int currentTimer = 0;
int duration = 60 * 1000;
@override
void initState() {
Wakelock.enable();
// Hide the status bar in Android
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
initCameras().then((value) {
cameras = value;
if (cameras != null) {
onNewCameraSelected(cameras![0]);
refreshAlreadyCapturedImages();
} else {
Toast.show("摄像头出错啦~");
}
});
fetchPoemDetail();
_timer = PausableTimer(
const Duration(milliseconds: 100),
() {
currentTimer += 100;
_timer
..reset()
..start();
if (currentTimer >= duration) {
stopRecordVideo();
}
setState(() {});
},
);
super.initState();
}
Future<void> fetchPoemDetail() async {
DioUtils.instance.asyncRequestNetwork<PoemEntity>(
Method.get,
"${HttpApi.poem}/${widget.poemId}",
params: [],
onSuccess: (data) {
_poem = data!.data!;
setState(() {});
},
onError: (code, msg) {},
);
}
Future<List<CameraDescription>?> initCameras() async {
try {
WidgetsFlutterBinding.ensureInitialized();
List<CameraDescription> cameras = await availableCameras();
return cameras;
} on CameraException catch (e) {
return null;
}
}
refreshAlreadyCapturedImages() async {
final directory = await getApplicationDocumentsDirectory();
List<FileSystemEntity> fileList = await directory.list().toList();
allFileList.clear();
List<Map<int, dynamic>> fileNames = [];
for (var file in fileList) {
if (file.path.contains('.jpg') || file.path.contains('.mp4')) {
allFileList.add(File(file.path));
String name = file.path.split('/').last.split('.').first;
fileNames.add({0: int.parse(name), 1: file.path.split('/').last});
}
}
}
Future<XFile?> takePicture() async {
final CameraController? cameraController = controller;
if (cameraController!.value.isTakingPicture) {
// A capture is already pending, do nothing.
return null;
}
try {
XFile file = await cameraController.takePicture();
return file;
} on CameraException catch (e) {
return null;
}
}
Future<void> startVideoRecording() async {
final CameraController? cameraController = controller;
if (controller!.value.isRecordingVideo) {
// A recording has already started, do nothing.
return;
}
try {
await cameraController!.startVideoRecording();
setState(() {
_isRecordingInProgress = true;
});
} on CameraException catch (e) {
// print('Error starting to record video: $e');
}
}
Future<XFile?> stopVideoRecording() async {
if (!controller!.value.isRecordingVideo) {
// Recording is already is stopped state
return null;
}
try {
XFile file = await controller!.stopVideoRecording();
setState(() {
_isRecordingInProgress = false;
});
return file;
} on CameraException catch (e) {
return null;
}
}
Future<void> pauseVideoRecording() async {
if (!controller!.value.isRecordingVideo) {
// Video recording is not in progress
return;
}
try {
await controller!.pauseVideoRecording();
} on CameraException catch (e) {
// print('Error pausing video recording: $e');
}
}
Future<void> resumeVideoRecording() async {
if (!controller!.value.isRecordingVideo) {
// No video recording was in progress
return;
}
try {
await controller!.resumeVideoRecording();
} on CameraException catch (e) {
// print('Error resuming video recording: $e');
}
}
void onNewCameraSelected(CameraDescription cameraDescription) async {
final previousCameraController = controller;
final CameraController cameraController = CameraController(
cameraDescription,
currentResolutionPreset,
imageFormatGroup: ImageFormatGroup.jpeg,
);
await previousCameraController?.dispose();
if (mounted) {
setState(() {
controller = cameraController;
});
}
// Update UI if controller updated
cameraController.addListener(() {
if (mounted) setState(() {});
});
try {
await cameraController.initialize();
} on CameraException catch (e) {
// print('Error initializing camera: $e');
}
if (mounted) {
setState(() {
_isCameraInitialized = controller!.value.isInitialized;
});
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
final CameraController? cameraController = controller;
// App state changed before we got the chance to initialize.
if (cameraController == null || !cameraController.value.isInitialized) {
return;
}
if (state == AppLifecycleState.inactive) {
cameraController.dispose();
} else if (state == AppLifecycleState.resumed) {
onNewCameraSelected(cameraController.description);
}
}
@override
void dispose() {
controller?.dispose();
videoController?.dispose();
///取消计时器
_timer.cancel();
Wakelock.disable();
super.dispose();
}
Future<void> stopRecordVideo() async {
try {
XFile? rawVideo = await stopVideoRecording();
File videoFile = File(rawVideo!.path);
int currentUnix = DateTime.now().millisecondsSinceEpoch;
final directory = await getApplicationDocumentsDirectory();
String fileFormat = videoFile.path.split('.').last;
_videoFile = await videoFile.copy(
'${directory.path}/$currentUnix.$fileFormat',
);
// TODO why pause!直接使用cancel()会出现问题,暂时这么解决
_timer.pause();
_gotoNext(currentUnix, fileFormat);
} catch (e) {
// print(e);
}
}
void _gotoNext(int currentUnix, String fileFormat) {
NavigatorUtils.push(
context,
'${PoemRouter.poemVideoPlayer}?url=$currentUnix.$fileFormat&id=${widget.id}&poemId=${widget.poemId}&type=${widget.type}',
);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: const MyAppBar(
isBack: true,
),
backgroundColor: Colors.black,
body: _isCameraInitialized
? Stack(
children: [
controller!.buildPreview(),
Padding(
padding: EdgeInsets.fromLTRB(10.px, 30.px, 10.px, 10.px),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_poem != null ? _poem!.title.toString() : "",
style: TextStyle(
color: Colors.white,
fontSize: 28.px,
),
),
Gaps.vGap10,
Text(
_poem != null ? _poem!.author.toString() : "",
style: TextStyle(
color: Colors.white,
fontSize: 15.px,
),
),
Gaps.vGap5,
Text(
_poem != null ? _poem!.content.toString() : "",
style: TextStyle(
color: Colors.white,
fontFamily: "ZCOOLXiaoWei",
fontSize: 25.px,
),
),
Gaps.vGap5,
Text(
"临者:老魔取西经",
style: TextStyle(
color: Colors.white,
fontSize: 15.px,
),
),
Text(
"2022年01月25日 辰时三刻",
style: TextStyle(
color: Colors.white,
fontSize: 15.px,
),
),
],
),
),
Padding(
padding: EdgeInsets.fromLTRB(
16.px,
8.px,
16.px,
8.px,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// Spacer(),
const Spacer(
flex: 1,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
InkWell(
onTap: _isRecordingInProgress
? () async {
if (controller!.value.isRecordingPaused) {
await resumeVideoRecording();
_timer.start();
} else {
await pauseVideoRecording();
_timer.pause();
}
}
: () {
setState(() {
_isCameraInitialized = false;
});
onNewCameraSelected(cameras![
_isRearCameraSelected ? 1 : 0]);
setState(() {
_isRearCameraSelected =
!_isRearCameraSelected;
});
},
child: Stack(
alignment: Alignment.center,
children: [
Icon(
Icons.circle,
color: Colors.black38,
size: 60.px,
),
_isRecordingInProgress
? controller!.value.isRecordingPaused
? Icon(
Icons.play_arrow,
color: Colors.white,
size: 30.px,
)
: Icon(
Icons.pause,
color: Colors.white,
size: 30.px,
)
: Icon(
_isRearCameraSelected
? Icons.camera_front
: Icons.camera_rear,
color: Colors.white,
size: 30.px,
),
],
),
),
InkWell(
onTap: () async {
if (_isRecordingInProgress) {
stopRecordVideo();
} else {
currentTimer = 0;
_timer
..reset()
..start();
await startVideoRecording();
}
},
child: Stack(
alignment: Alignment.center,
children: [
Icon(
Icons.circle,
color: _isVideoCameraSelected
? Colors.white
: Colors.white38,
size: 80.px,
),
_isRecordingInProgress
? SizedBox(
width: 60.px,
height: 60.px,
child: CircularProgressIndicator(
strokeWidth: 5.px,
value: currentTimer / duration,
),
)
: Container(),
Icon(
Icons.circle,
color: _isVideoCameraSelected
? Colors.red
: Colors.white,
size: 65.px,
),
_isRecordingInProgress
? Container()
: Text(
"60s",
style: TextStyle(
fontSize: 12.px,
color: Colors.white,
),
),
_isVideoCameraSelected &&
_isRecordingInProgress
? Icon(
Icons.stop_rounded,
color: Colors.white,
size: 32.px,
)
: Container(),
],
),
),
InkWell(
onTap: () {},
child: Stack(
alignment: Alignment.center,
children: [
Icon(
Icons.circle,
color: Colors.black38,
size: 60.px,
),
Icon(
Icons.photo_album,
color: Colors.white,
size: 30.px,
),
],
),
),
],
),
],
),
),
],
)
: const Center(
child: Text(
'开启摄像头..',
style: TextStyle(color: Colors.white),
),
),
),
);
}
}