Blame view

lib/pages/video/zone/video_zone_player_page.dart 11.5 KB
383462ef   吴启风   feat: 新增视频专区列表与播放功能
1
2
  import 'dart:async';
  
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
3
4
  import 'package:chewie/chewie.dart';
  import 'package:flutter/foundation.dart';
383462ef   吴启风   feat: 新增视频专区列表与播放功能
5
  import 'package:flutter/material.dart';
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
6
  import 'package:flutter/services.dart';
383462ef   吴启风   feat: 新增视频专区列表与播放功能
7
8
  import 'package:video_player/video_player.dart';
  import 'package:wow_english/common/request/dao/video_dao.dart';
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
9
  import 'package:wow_english/common/utils/video_progress_cache.dart';
383462ef   吴启风   feat: 新增视频专区列表与播放功能
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  
  import 'video_zone_item.dart';
  
  class VideoZonePlayerPage extends StatefulWidget {
    const VideoZonePlayerPage({
      super.key,
      required this.items,
      this.initialVideoId,
    }) : assert(items.length > 0, '视频播放列表不能为空');
  
    final List<VideoZoneItem> items;
    final int? initialVideoId;
  
    @override
    State<VideoZonePlayerPage> createState() => _VideoZonePlayerPageState();
  }
  
  class _VideoZonePlayerPageState extends State<VideoZonePlayerPage>
      with WidgetsBindingObserver {
    VideoPlayerController? _controller;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
30
31
    ChewieController? _chewieController;
    Timer? _cacheTimer;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
32
33
    late int _currentIndex;
    double _playbackSpeed = 1;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
34
35
    bool _switchingVideo = false;
    bool _handlingCompletion = false;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
36
    bool? _lastIsPlaying;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
37
38
39
40
41
42
43
44
45
    int? _completedReportedVideoId;
    Object? _loadError;
  
    VideoZoneItem get _currentItem => widget.items[_currentIndex];
  
    @override
    void initState() {
      super.initState();
      WidgetsBinding.instance.addObserver(this);
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
46
47
48
      unawaited(
        SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky),
      );
383462ef   吴启风   feat: 新增视频专区列表与播放功能
49
50
51
52
53
54
55
56
      final index = widget.initialVideoId == null
          ? 0
          : widget.items.indexWhere((item) => item.id == widget.initialVideoId);
      _currentIndex = index < 0 ? 0 : index;
      _loadCurrentVideo();
    }
  
    Future<void> _loadCurrentVideo() async {
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
57
58
      final useCupertinoControls = defaultTargetPlatform == TargetPlatform.iOS;
      _cacheTimer?.cancel();
383462ef   吴启风   feat: 新增视频专区列表与播放功能
59
      final oldController = _controller;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
60
61
62
63
      final oldChewieController = _chewieController;
      if (oldController?.value.isInitialized == true) {
        _playbackSpeed = oldController!.value.playbackSpeed;
      }
383462ef   吴启风   feat: 新增视频专区列表与播放功能
64
      oldController?.removeListener(_onVideoChanged);
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
65
      _lastIsPlaying = null;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
66
67
68
      final controller =
          VideoPlayerController.networkUrl(Uri.parse(_currentItem.videoUrl));
      _controller = controller;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
69
      _chewieController = null;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
70
71
72
73
      _loadError = null;
      if (mounted) {
        setState(() {});
      }
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
74
      oldChewieController?.dispose();
383462ef   吴启风   feat: 新增视频专区列表与播放功能
75
76
77
      await oldController?.dispose();
  
      try {
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
78
        await controller.initialize().timeout(const Duration(seconds: 20));
383462ef   吴启风   feat: 新增视频专区列表与播放功能
79
80
81
82
83
84
        if (!mounted || controller != _controller) {
          await controller.dispose();
          return;
        }
        await controller.setLooping(false);
        await controller.setPlaybackSpeed(_playbackSpeed);
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
85
86
87
88
89
        final savedProgress = await _resumeProgressFor(_currentItem.id);
        if (!mounted || controller != _controller) {
          await controller.dispose();
          return;
        }
383462ef   吴启风   feat: 新增视频专区列表与播放功能
90
91
92
93
        if (savedProgress > 0 &&
            savedProgress < controller.value.duration.inSeconds) {
          await controller.seekTo(Duration(seconds: savedProgress));
        }
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
94
        _lastIsPlaying = controller.value.isPlaying;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
95
        controller.addListener(_onVideoChanged);
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
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
        _chewieController = ChewieController(
          videoPlayerController: controller,
          autoPlay: true,
          looping: false,
          allowFullScreen: false,
          allowPlaybackSpeedChanging: true,
          draggableProgressBar: true,
          allowedScreenSleep: false,
          playbackSpeeds: const [0.5, 0.75, 1, 1.25, 1.5, 2],
          customControls:
              useCupertinoControls ? null : const _VideoMaterialControls(),
          optionsTranslation: OptionsTranslation(
            playbackSpeedButtonText: '播放速度',
            cancelButtonText: '取消',
          ),
          materialProgressColors: ChewieProgressColors(
            playedColor: const Color(0xFF00B6F1),
            handleColor: const Color(0xFF00B6F1),
            bufferedColor: Colors.white54,
            backgroundColor: Colors.white24,
          ),
          cupertinoProgressColors: ChewieProgressColors(
            playedColor: const Color(0xFF00B6F1),
            handleColor: const Color(0xFF00B6F1),
            bufferedColor: Colors.white54,
            backgroundColor: Colors.white24,
          ),
          placeholder: const ColoredBox(color: Colors.black),
          errorBuilder: (_, __) => const Center(
            child: Text(
              '视频播放失败',
              style: TextStyle(color: Colors.white, fontSize: 18),
            ),
          ),
        );
383462ef   吴启风   feat: 新增视频专区列表与播放功能
131
        _handlingCompletion = false;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
132
133
134
135
136
137
138
        _cacheTimer = Timer.periodic(
          const Duration(seconds: 30),
          (_) {
            if (_controller?.value.isPlaying == true) {
              unawaited(_cacheCurrentProgress());
            }
          },
383462ef   吴启风   feat: 新增视频专区列表与播放功能
139
140
141
142
143
144
145
146
147
148
149
150
        );
        setState(() {});
      } catch (error) {
        if (mounted && controller == _controller) {
          setState(() => _loadError = error);
        }
      }
    }
  
    void _onVideoChanged() {
      final controller = _controller;
      if (!mounted || controller == null) return;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
151
152
153
154
155
      final isPlaying = controller.value.isPlaying;
      if (_lastIsPlaying != null && _lastIsPlaying != isPlaying) {
        unawaited(_cacheCurrentProgress());
      }
      _lastIsPlaying = isPlaying;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
156
157
158
159
160
161
      if (controller.value.isCompleted &&
          !_switchingVideo &&
          !_handlingCompletion &&
          _completedReportedVideoId != _currentItem.id) {
        _handlingCompletion = true;
        unawaited(_handleVideoCompleted());
383462ef   吴启风   feat: 新增视频专区列表与播放功能
162
      }
383462ef   吴启风   feat: 新增视频专区列表与播放功能
163
164
165
166
167
    }
  
    Future<void> _playNext({bool currentCompleted = false}) async {
      if (_switchingVideo || _currentIndex >= widget.items.length - 1) return;
      _switchingVideo = true;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
168
      await _reportCurrentProgress(completed: currentCompleted);
383462ef   吴启风   feat: 新增视频专区列表与播放功能
169
170
171
172
173
174
175
176
177
      setState(() => _currentIndex++);
      await _loadCurrentVideo();
      _switchingVideo = false;
    }
  
    Future<void> _handleVideoCompleted() async {
      if (_currentIndex < widget.items.length - 1) {
        await _playNext(currentCompleted: true);
      } else {
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
178
        await _reportCurrentProgress(completed: true);
383462ef   吴启风   feat: 新增视频专区列表与播放功能
179
180
181
182
      }
      _handlingCompletion = false;
    }
  
383462ef   吴启风   feat: 新增视频专区列表与播放功能
183
184
185
    @override
    void dispose() {
      WidgetsBinding.instance.removeObserver(this);
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
186
187
188
189
      unawaited(
        SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky),
      );
      _cacheTimer?.cancel();
383462ef   吴启风   feat: 新增视频专区列表与播放功能
190
      _controller?.removeListener(_onVideoChanged);
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
191
192
      unawaited(_reportCurrentProgress());
      _chewieController?.dispose();
383462ef   吴启风   feat: 新增视频专区列表与播放功能
193
194
195
196
197
198
      _controller?.dispose();
      super.dispose();
    }
  
    @override
    void didChangeAppLifecycleState(AppLifecycleState state) {
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
199
200
201
202
203
      if (state == AppLifecycleState.resumed) {
        unawaited(
          SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky),
        );
      } else if (state == AppLifecycleState.inactive ||
383462ef   吴启风   feat: 新增视频专区列表与播放功能
204
205
          state == AppLifecycleState.paused ||
          state == AppLifecycleState.detached) {
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
206
        unawaited(_cacheCurrentProgress());
383462ef   吴启风   feat: 新增视频专区列表与播放功能
207
208
209
      }
    }
  
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
210
    Future<void> _reportCurrentProgress({bool? completed}) async {
383462ef   吴启风   feat: 新增视频专区列表与播放功能
211
212
      final controller = _controller;
      if (controller == null || !controller.value.isInitialized) return;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
213
214
      final currentItem = _currentItem;
      final durationSeconds = controller.value.duration.inSeconds;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
215
216
217
      final progressSeconds = controller.value.position.inSeconds
          .clamp(0, durationSeconds > 0 ? durationSeconds : 0);
      final isCompleted = completed ?? controller.value.isCompleted;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
218
219
220
221
222
223
224
      await _persistCachedProgress(
        videoId: currentItem.id,
        progressSeconds: progressSeconds,
        durationSeconds: durationSeconds,
        completed: isCompleted,
      );
      if (isCompleted && _completedReportedVideoId == currentItem.id) return;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
225
226
      try {
        await VideoDao.savePlayRecord(
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
227
          videoId: currentItem.id,
383462ef   吴启风   feat: 新增视频专区列表与播放功能
228
229
230
231
          progressSeconds: progressSeconds,
          durationSeconds: durationSeconds,
          completed: isCompleted,
        );
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
232
        if (isCompleted) _completedReportedVideoId = currentItem.id;
383462ef   吴启风   feat: 新增视频专区列表与播放功能
233
234
235
236
237
      } catch (error) {
        debugPrint('保存视频播放记录失败: $error');
      }
    }
  
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
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
    Future<int> _resumeProgressFor(int videoId) async {
      try {
        final cached = await VideoProgressCache.get(videoId);
        if (cached != null) return cached.progressSeconds;
      } catch (error) {
        debugPrint('读取本地视频播放进度失败: $error');
      }
      return 0;
    }
  
    Future<void> _cacheCurrentProgress() async {
      final controller = _controller;
      if (controller == null || !controller.value.isInitialized) return;
      final currentItem = _currentItem;
      final durationSeconds = controller.value.duration.inSeconds;
      final progressSeconds = controller.value.position.inSeconds
          .clamp(0, durationSeconds > 0 ? durationSeconds : 0);
      await _persistCachedProgress(
        videoId: currentItem.id,
        progressSeconds: progressSeconds,
        durationSeconds: durationSeconds,
        completed: controller.value.isCompleted,
      );
    }
  
    Future<void> _persistCachedProgress({
      required int videoId,
      required int progressSeconds,
      required int durationSeconds,
      required bool completed,
    }) async {
      try {
        if (completed) {
          await VideoProgressCache.remove(videoId);
        } else {
          await VideoProgressCache.save(
            videoId: videoId,
            progressSeconds: progressSeconds,
            durationSeconds: durationSeconds,
          );
        }
      } catch (error) {
        debugPrint('保存本地视频播放进度失败: $error');
      }
    }
  
383462ef   吴启风   feat: 新增视频专区列表与播放功能
284
285
286
    @override
    Widget build(BuildContext context) {
      final controller = _controller;
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
287
288
289
290
291
292
293
      final chewieController = _chewieController;
      return MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: Scaffold(
          backgroundColor: Colors.black,
          body: Stack(
383462ef   吴启风   feat: 新增视频专区列表与播放功能
294
295
            fit: StackFit.expand,
            children: [
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
296
297
298
              if (controller?.value.isInitialized == true &&
                  chewieController != null)
                Chewie(controller: chewieController)
383462ef   吴启风   feat: 新增视频专区列表与播放功能
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
              else if (_loadError != null)
                Center(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const Text('视频加载失败',
                          style: TextStyle(color: Colors.white, fontSize: 18)),
                      const SizedBox(height: 12),
                      FilledButton(
                          onPressed: _loadCurrentVideo, child: const Text('重试')),
                    ],
                  ),
                )
              else
                const Center(child: CircularProgressIndicator()),
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
314
315
316
317
              SafeArea(
                top: false,
                child: Align(
                  alignment: Alignment.topLeft,
383462ef   吴启风   feat: 新增视频专区列表与播放功能
318
319
                  child: Row(
                    children: [
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
320
321
322
323
324
                      IconButton(
                        onPressed: () => Navigator.of(context).pop(),
                        icon: const Icon(Icons.arrow_back_ios_new,
                            color: Colors.white),
                      ),
383462ef   吴启风   feat: 新增视频专区列表与播放功能
325
                      Expanded(
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
326
327
328
329
330
331
                        child: Text(
                          _currentItem.title,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style:
                              const TextStyle(color: Colors.white, fontSize: 20),
383462ef   吴启风   feat: 新增视频专区列表与播放功能
332
333
                        ),
                      ),
383462ef   吴启风   feat: 新增视频专区列表与播放功能
334
335
336
                    ],
                  ),
                ),
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
337
              ),
383462ef   吴启风   feat: 新增视频专区列表与播放功能
338
339
340
341
342
            ],
          ),
        ),
      );
    }
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
343
  }
383462ef   吴启风   feat: 新增视频专区列表与播放功能
344
  
7e98b732   吴启风   feat: 完善视频播放与本地进度缓存
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
  class _VideoMaterialControls extends StatelessWidget {
    const _VideoMaterialControls();
  
    @override
    Widget build(BuildContext context) {
      return Theme(
        data: Theme.of(context).copyWith(
          iconButtonTheme: IconButtonThemeData(
            style: IconButton.styleFrom(
              minimumSize: const Size.square(72),
              padding: const EdgeInsets.all(20),
            ),
          ),
        ),
        child: const MaterialControls(),
      );
383462ef   吴启风   feat: 新增视频专区列表与播放功能
361
362
    }
  }