reading_bloc.dart 15.4 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
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wow_english/common/extension/string_extension.dart';
import 'package:wow_english/pages/reading/widgets/ReadingModeType.dart';
import 'package:wow_english/pages/section/subsection/base_section/bloc.dart';
import 'package:wow_english/pages/section/subsection/base_section/event.dart';
import 'package:wow_english/pages/section/subsection/base_section/state.dart';

import '../../../common/core/user_util.dart';
import '../../../common/permission/permissionRequester.dart';
import '../../../common/request/dao/listen_dao.dart';
import '../../../common/request/exception.dart';
import '../../../common/utils/click_with_music_controller.dart';
import '../../../common/utils/show_star_reward_dialog.dart';
import '../../../models/course_process_entity.dart';
import '../../../models/singsound_result_detail_entity.dart';
import '../../../models/voice_result_type.dart';
import '../../../route/route.dart';
import '../../../utils/loading.dart';

import '../../../utils/log_util.dart';

part 'reading_event.dart';

part 'reading_state.dart';

enum VoicePlayState {
  ///未知
  unKnow,

  ///播放中
  playing,

  ///播放完成
  completed,

  ///播放终止
  stop
}

class ReadingPageBloc
    extends BaseSectionBloc<ReadingPageEvent, ReadingPageState> {
  final PageController pageController;

  final String courseLessonId;

  ///当前页索引
  int _currentPage = 0;

  ///当前播放模式
  ReadingModeType _currentMode = ReadingModeType.manual;

  int get currentPage => _currentPage + 1;

  ReadingModeType get currentMode => _currentMode;

  CourseProcessEntity? _entity;

  CourseProcessEntity? get entity => _entity;

  ///正在评测
  bool _isRecording = false;

  bool get isRecording => _isRecording;

  ///原始音频是否正在播放
  bool _isOriginAudioPlaying = false;

  bool get isOriginAudioPlaying => _isOriginAudioPlaying;

  ///录音音频是否正在播放
  bool _isRecordAudioPlaying = false;

  bool get isRecordAudioPlaying => _isRecordAudioPlaying;

  ///正在播放音频状态
  VoicePlayState _voicePlayState = VoicePlayState.unKnow;

  VoicePlayState get voicePlayState => _voicePlayState;

  late MethodChannel methodChannel;

  late AudioPlayer audioPlayer;

  final BuildContext context;

  ReadingPageBloc(this.context, this.pageController, this.courseLessonId)
      : super(ReadingPageInitial()) {
    on<CurrentPageIndexChangeEvent>(_pageControllerChange);
    on<CurrentModeChangeEvent>(_playModeChange);
    // pageController.addListener(() {
    //   _currentPage = pageController.page!.round();
    // });
    on<RequestDataEvent>(_requestData);
    on<InitBlocEvent>((event, emit) {
      //音频播放器
      audioPlayer = AudioPlayer();
      audioPlayer.onPlayerStateChanged.listen((event) async {
        Log.d("播放状态变化 event=$event");
        if (event == PlayerState.completed) {
          debugPrint('播放完成');
          _voicePlayState = VoicePlayState.completed;
          _onAudioPlayComplete();
        }
        if (event == PlayerState.stopped) {
          debugPrint('播放结束');
          _voicePlayState = VoicePlayState.stop;
        }

        if (event == PlayerState.playing) {
          debugPrint('正在播放中');
          _voicePlayState = VoicePlayState.playing;
        }

        if (event == PlayerState.disposed) {
          debugPrint('播放器释放');
          _voicePlayState = VoicePlayState.unKnow;
        }

        if (isClosed) {
          return;
        }
        add(VoicePlayStateChangeEvent());
      });

      methodChannel =
          const MethodChannel('wow_english/sing_sound_method_channel');
      methodChannel.invokeMethod('initVoiceSdk', {}); //初始化评测
      methodChannel.setMethodCallHandler((call) async {
        Log.d(
            "setMethodCallHandler method=${call.method} arguments=${call.arguments}");
        if (call.method == 'voiceResult') {
          //评测结果
          await audioPlayer.setAudioContext(AudioContext());
          await audioPlayer.setBalance(0.0);

          add(XSVoiceResultEvent(call.arguments));
          return;
        }

        if (call.method == 'voiceStart') {
          //评测开始
          if (kDebugMode) {
            print('评测开始');
          }
          _isRecording = true;
          add(OnXSVoiceStateChangeEvent());
          return;
        }

        if (call.method == 'voiceEnd' || call.method == 'voiceCancel') {
          //评测结束or评测取消
          if (kDebugMode) {
            print(call.method == 'voiceEnd' ? '评测结束' : '评测取消');
          }
          await audioPlayer.setAudioContext(AudioContext());
          await audioPlayer.setBalance(0.0);

          _isRecording = false;
          add(OnXSVoiceStateChangeEvent());
          return;
        }

        if (call.method == 'voiceFail') {
          //评测失败
          _isRecording = false;
          await audioPlayer.setAudioContext(AudioContext());
          await audioPlayer.setBalance(0.0);

          EasyLoading.showToast('评测失败');
          return;
        }
      });
    });
    on<VoicePlayStateChangeEvent>(_voicePlayStateChange);
    on<PlayOriginalAudioEvent>(_playOriginalAudio);
    on<XSVoiceInitEvent>(_initVoiceSdk);
    on<XSVoiceStartEvent>(_voiceXsStart);
    on<XSVoiceStopEvent>(_voiceXsStop);
    on<XSVoiceResultEvent>(_voiceXsResult);
    on<OnXSVoiceStateChangeEvent>(_onVoiceXsStateChange);

    on<PlayRecordAudioEvent>(_playRecordAudio);
  }

  @override
  Future<void> close() {
    pageController.dispose();
    audioPlayer.release();
    audioPlayer.dispose();
    _voiceXsCancel(force: true);
    return super.close();
  }

  void _pageControllerChange(CurrentPageIndexChangeEvent event,
      Emitter<ReadingPageState> emitter) async {
    _currentPage = event.pageIndex;
    _voiceXsCancel();
    _playOriginalAudioInner(null, forcePlay: true);
    emitter(CurrentPageIndexState());
  }

  void _playModeChange(
      CurrentModeChangeEvent event, Emitter<ReadingPageState> emitter) async {
    if (_currentMode == ReadingModeType.auto) {
      _currentMode = ReadingModeType.manual;
    } else {
      _currentMode = ReadingModeType.auto;
    }
    emitter(CurrentModeState());
  }

  ///请求数据
  void _requestData(
      RequestDataEvent event, Emitter<ReadingPageState> emitter) async {
    try {
      await loading(() async {
        _entity = await ListenDao.process(courseLessonId);
        Log.d("reading page entity: ${_entity!.toJson()}");
        emitter(RequestDataState());
      });
    } catch (e) {
      if (e is ApiException) {
        EasyLoading.showToast(e.message ?? '请求失败,请检查网络连接');
      }
    }
  }

  /// 播放绘本原音
  void _playOriginalAudio(
      PlayOriginalAudioEvent event, Emitter<ReadingPageState> emitter) async {
    _playOriginalAudioInner(event.url);
  }

  ///播放原音音频
  /// - [force]: 是否强制播放(true:不管当前状态如何,都会播放目标原音音频,比如翻页场景)
  /// (false:如果正在播放,暂停播放,比如点击播放按钮场景)
  void _playOriginalAudioInner(String? audioUrl,
      {bool forcePlay = false}) async {
    if (_isRecordAudioPlaying) {
      await audioPlayer.stop();
      _isRecordAudioPlaying = false;
    }
    Log.d(
        "_playOriginalAudio _isRecordAudioPlaying=$_isRecordAudioPlaying _isOriginAudioPlaying=$_isOriginAudioPlaying url=$audioUrl");
    if (_isOriginAudioPlaying) {
      await audioPlayer.stop();
      _isOriginAudioPlaying = false;
      if (forcePlay) {
        audioUrl ??= currentPageData()?.audioUrl ?? '';
        await _playAudio(audioUrl);
        _isOriginAudioPlaying = true;
      }
    } else {
      audioUrl ??= currentPageData()?.audioUrl ?? '';
      await _playAudio(audioUrl);
      _isOriginAudioPlaying = true;
    }
  }

  /// 播放录音
  void _playRecordAudio(
      PlayRecordAudioEvent event, Emitter<ReadingPageState> emitter) async {
    _playRecordAudioInner();
  }

  Future<void> _playRecordAudioInner() async {
    Log.d(
        "_playRecordAudioInner _isOriginAudioPlaying=$_isOriginAudioPlaying _isRecordAudioPlaying=$_isRecordAudioPlaying url=${currentPageData()?.recordUrl}");
    if (_isOriginAudioPlaying) {
      ///如果正在播放原音,暂停
      await audioPlayer.stop();
      _isOriginAudioPlaying = false;
    }

    if (_isRecordAudioPlaying) {
      await audioPlayer.stop();
      _isRecordAudioPlaying = false;
    } else {
      final recordAudioUrl = currentPageData()?.recordUrl;
      await _playAudio(recordAudioUrl);
      _isRecordAudioPlaying = true;
    }
    // emitter(VoicePlayStateChange());
  }

  Future<void> _playAudio(String? audioUrl) async {
    if (audioUrl!.isNotEmpty) {
      await audioPlayer.play(UrlSource(audioUrl),
          balance: 0.0, ctx: AudioContext());
    }
  }

  int dataCount() {
    return _entity?.readings?.length ?? 0;
  }

  CourseProcessReadings? currentPageData() {
    return _entity?.readings?[_currentPage];
  }

  ///当前页绘本跟读内容
  String readingContent() {
    return currentPageData()?.word?.trim() ?? '';
  }

  /// 结合单词分数返回带颜色的TextSpan数组
  List<TextSpan>? displayContent() {
    // return _textController.text.isNotEmpty ? _textController.text : readingContent();
    // 创建用于展示每个单词的 TextSpan 列表
    if (currentPageData() == null) {
      return null;
    }
    List<SingsoundResultDetailEntity> resultDetails;
    if (currentPageData()?.resultDetails != null) {
      resultDetails = currentPageData()!.resultDetails!;
    } else {
      List<String>? wordList = currentPageData()?.word?.split(RegExp(r'\s+'));
      resultDetails = wordList!
          .map(
              (word) => SingsoundResultDetailEntity.withCharAndScore(word, 0))
          .toList();
    }
    List<TextSpan> textSpans = resultDetails.asMap().entries.map((entry) {
      int index = entry.key;
      SingsoundResultDetailEntity detail = entry.value;
      // Check if this is the last word in the list
      bool isLastWord = index == resultDetails.length - 1;
      return TextSpan(
        text: '${detail.char}${isLastWord ? '' : ' '}',
        style: TextStyle(
          color: detail.score > 80
              ? const Color(0XFF35C137)
              : const Color(0xFF333333),
          fontSize: 20.sp,
        ),
      );
    }).toList();
    return textSpans;
  }

  void nextPage() {
    if (currentPage >= dataCount()) {
      sectionComplete(() {
        popPage(data: {
          'currentStep': currentPage,
          'courseLessonId': courseLessonId,
          'isCompleted': true,
          'nextSection': true
        });
      }, againSectionTap: () {
        pageController.jumpToPage(0);
      });
    } else {
      _currentPage += 1;
      pageController.nextPage(
        duration: const Duration(milliseconds: 250),
        curve: Curves.ease,
      );
    }
  }

  ///初始化SDK
  _initVoiceSdk(
      XSVoiceInitEvent event, Emitter<ReadingPageState> emitter) async {
    methodChannel.invokeMethod('initVoiceSdk', event.data);
  }

  ///先声测试
  void _voiceXsStart(
      XSVoiceStartEvent event, Emitter<ReadingPageState> emitter) async {
    await _stopAudio();
    startRecord(event.content);
  }

  ///开始录音
  void startRecord(String content) async {
    // 调用封装好的权限检查和请求方法
    bool result = await requestPermission(
        context, Permission.microphone, "录音", "用于开启录音,识别您的开口作答并给出反馈");
    if (result) {
      methodChannel.invokeMethod('startVoice', {
        'word': content,
        'type': '0',
        'userId': UserUtil.getUser()?.id.toString()
      });
    }
  }

  void _voiceXsResult(
      XSVoiceResultEvent event, Emitter<ReadingPageState> emitter) async {
    final Map args = event.message as Map;
    final result = args['result'] as Map;
    Log.d("_voiceXsResult result=$result");
    final overall = result['overall'].toString();
    List<dynamic> resultDetailsJsons = result['details'];
    // 提取 score 和 char 字段
    List<SingsoundResultDetailEntity> detailEntities = [];
    for (var detail in resultDetailsJsons) {
      int score = detail['score'] as int;
      String char = detail['char'] as String;
      detailEntities
          .add(SingsoundResultDetailEntity.withCharAndScore(char, score));
    }

    ///todo 后面可以考虑要不要传自己的服务器
    final recordFileUrl = args['audioUrl'].toString();
    int score = int.parse(overall);
    currentPageData()?.recordScore = overall;
    currentPageData()?.recordUrl = recordFileUrl.assetMp3;
    currentPageData()?.resultDetails = detailEntities;
    add(OnXSVoiceStateChangeEvent());

    final voiceResult = VoiceResultType.fromScore(score);
    if (voiceResult.lottieFilePath != null) {
      showCheerRewardDialog(context, lottieFile: voiceResult.lottieFilePath!);
    }
    await ClickWithMusicController.instance
        .playMusicAndPerformAction(context, voiceResult.audioType, () async {
      ///完成录音后紧接着播放录音
      await _playRecordAudioInner();
      if (isLastPage()) {
        sectionComplete(() {
          popPage(data: {
            'currentStep': currentPage,
            'courseLessonId': courseLessonId,
            'isCompleted': true,
            'nextSection': true
          });
        }, againSectionTap: () {
          _resetLocalResult();
          pageController.jumpToPage(0);
        });
      }
    });
  }

  ///终止评测
  void _voiceXsStop(
      XSVoiceStopEvent event, Emitter<ReadingPageState> emitter) async {
    methodChannel.invokeMethod('stopVoice');
  }

  ///取消评测(用于处理退出页面后录音未停止等异常情况的保护操作)
  void _voiceXsCancel({bool force = false}) {
    Log.d("取消评测 _voiceXsCancel _isRecording=$_isRecording");
    if (_isRecording || force) {
      methodChannel.invokeMethod('cancelVoice');
    }
  }

  void _voicePlayStateChange(VoicePlayStateChangeEvent event,
      Emitter<ReadingPageState> emitter) async {
    emitter(VoicePlayStateChange());
  }

  void _onAudioPlayComplete() {
    if (_isRecordAudioPlaying && _currentMode == ReadingModeType.auto) {
      nextPage();
    }

    Log.d(
        "_onAudioPlayComplete _isOriginAudioPlaying=$_isOriginAudioPlaying _voicePlayState=$_voicePlayState recordUrl=${currentPageData()?.recordUrl?.isNotEmpty}");
    if (_isOriginAudioPlaying &&
        currentPageData()?.recordUrl?.isNotEmpty != true) {
      ///如果刚刚完成原音播放&&录音为空,则开始录音
      startRecord(currentPageData()?.word ?? '');
    }

    _isOriginAudioPlaying = false;
    _isRecordAudioPlaying = false;
  }

  Future<void> _stopAudio() async {
    await audioPlayer.stop();
    _isOriginAudioPlaying = false;
    _isRecordAudioPlaying = false;
  }

  void _onVoiceXsStateChange(OnXSVoiceStateChangeEvent event,
      Emitter<ReadingPageState> emitter) async {
    emitter(XSVoiceTestState());
  }

  ///是否是最后一页
  bool isLastPage() {
    return currentPage == dataCount();
  }

  ///重置数据
  void _resetLocalResult() {
    _entity?.readings?.forEach((element) {
      element.recordScore = null;
      element.recordUrl = null;
    });
  }
}