topic_picture_bloc.dart 12.6 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
import 'dart:async';

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:permission_handler/permission_handler.dart';
import 'package:wow_english/common/extension/string_extension.dart';
import 'package:wow_english/common/request/dao/listen_dao.dart';
import 'package:wow_english/common/request/exception.dart';
import 'package:wow_english/models/course_process_entity.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 'package:wow_english/utils/audio_player_util.dart';
import 'package:wow_english/utils/toast_util.dart';

import '../../../common/permission/permissionRequester.dart';
import '../../../common/utils/click_with_music_controller.dart';
import '../../../common/utils/show_star_reward_dialog.dart';
import '../../../route/route.dart';
import '../../../utils/log_util.dart';

part 'topic_picture_event.dart';

part 'topic_picture_state.dart';

enum VoicePlayState {
  ///未知
  unKnow,

  ///播放中
  playing,

  ///播放完成
  completed,

  ///播放终止
  stop
}

class TopicPictureBloc
    extends BaseSectionBloc<TopicPictureEvent, TopicPictureState> {
  final PageController pageController;

  final String courseLessonId;

  int _currentPage = 0;

  int _selectItem = -1;

  CourseProcessEntity? _entity;

  CourseProcessEntity? get entity => _entity;

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

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

  // 是否是回答(选择)结果音效
  bool _isResultSoundPlaying = false;

  bool get isResultSoundPlaying => _isResultSoundPlaying;

  // 答对播放音效时禁止任何点击(选择)操作
  bool _forbiddenWhenCorrect = false;

  bool get forbiddenWhenCorrect => _forbiddenWhenCorrect;

  int get currentPage => _currentPage + 1;

  int get selectItem => _selectItem;

  bool get isRecording => _isRecording;

  VoicePlayState get voicePlayState => _voicePlayState;

  late MethodChannel methodChannel;

  late AudioPlayer audioPlayer;

  final BuildContext context;

  final Color? moduleColor;

  TopicPictureBloc(
      this.context, this.pageController, this.courseLessonId, this.moduleColor)
      : super(TopicPictureInitial()) {
    on<CurrentPageIndexChangeEvent>(_pageControllerChange);
    on<VoicePlayStateChangeEvent>(_voicePlayStateChange);
    on<XSVoiceResultEvent>(_voiceXsResult);
    on<XSVoiceInitEvent>(_initVoiceSdk);
    on<SelectItemEvent>(_selectItemLoad);
    on<RequestDataEvent>(_requestData);
    on<XSVoiceStartEvent>(_voiceXsStart);
    on<XSVoiceStopEvent>(_voiceXsStop);
    on<VoicePlayEvent>(_questionVoicePlay);
    on<InitBlocEvent>((event, emit) {
      //音频播放器
      audioPlayer = AudioPlayer();
      audioPlayer.onPlayerStateChanged.listen((event) async {
        debugPrint(
            '播放状态变化 _voicePlayState=$_voicePlayState event=$event _isResultSoundPlaying=$_isResultSoundPlaying _forbiddenWhenCorrect=$_forbiddenWhenCorrect');
        if (_isResultSoundPlaying) {
          if (event != PlayerState.playing) {
            _isResultSoundPlaying = false;
            if (_forbiddenWhenCorrect) {
              _forbiddenWhenCorrect = false;
              debugPrint('播放完成后解除禁止');
              if (event == PlayerState.completed) {
                if (isLastPage()) {
                  showStepPage();
                } else {
                  // 答对后且播放完自动翻页
                  pageController.nextPage(
                    duration: const Duration(milliseconds: 250),
                    curve: Curves.ease,
                  );
                }
              }
            }
          }
        } else {
          if (event == PlayerState.completed) {
            debugPrint('播放完成');
            _voicePlayState = VoicePlayState.completed;
          }
          if (event == PlayerState.stopped) {
            debugPrint('播放结束');
            _voicePlayState = VoicePlayState.stop;
          }

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

      methodChannel =
          const MethodChannel('wow_english/sing_sound_method_channel');
      methodChannel.setMethodCallHandler((call) async {
        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('评测开始');
          }
          return;
        }

        if (call.method == 'voiceEnd') {
          await audioPlayer.setAudioContext(AudioContext());
          await audioPlayer.setBalance(0.0);
          //评测结束
          if (kDebugMode) {
            print('评测结束');
          }
          return;
        }

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

          EasyLoading.showToast('评测失败');
          return;
        }
      });
    });
  }

  @override
  Future<void> close() {
    pageController.dispose();
    audioPlayer.release();
    audioPlayer.dispose();
    _isResultSoundPlaying = false;
    _forbiddenWhenCorrect = false;
    _voiceXsCancel();
    return super.close();
  }

  ///请求数据
  void _requestData(
      RequestDataEvent event, Emitter<TopicPictureState> emitter) async {
    try {
      _entity = await ListenDao.process(courseLessonId);
      emitter(RequestDataState());
    } catch (e) {
      if (e is ApiException) {
        showToast(e.message ?? '请求失败,请检查网络连接');
      }
    }
  }

  ///页面切换
  void _pageControllerChange(CurrentPageIndexChangeEvent event,
      Emitter<TopicPictureState> emitter) async {
    await closePlayerResource();
    debugPrint('翻页 $_currentPage->${event.pageIndex}');
    if (_currentPage == _entity?.topics?.length) {
      return;
    }
    _currentPage = event.pageIndex;
    final topics = _entity?.topics?[_currentPage];
    if (topics?.type != 3 && topics?.type != 4) {
      if (topics?.audioUrl != null) {
        final urlStr = topics?.audioUrl ?? '';
        if (urlStr.isNotEmpty) {
          debugPrint(urlStr);
          await audioPlayer.play(UrlSource(urlStr));
        }
      }
    }
    _selectItem = -1;
    emitter(CurrentPageIndexState());
  }

  ///选择
  void _selectItemLoad(
      SelectItemEvent event, Emitter<TopicPictureState> emitter) async {
    if (_forbiddenWhenCorrect) {
      return;
    }
    _selectItem = event.selectIndex;
    if (checkAnswerRight(_selectItem) == true) {
      _playResultSound(true);
      showStarRewardDialog(context);
      // showToast('恭喜你,答对啦!',duration: const Duration(seconds: 2));
    } else {
      _playResultSound(false);
      // showToast('继续加油哦',duration: const Duration(seconds: 2));
    }
    emitter(SelectItemChangeState());
  }

  ///为空则数据异常,用于是否晃动时需要
  bool? checkAnswerRight(int selectIndex) {
    CourseProcessTopics? topics = _entity?.topics?[_currentPage];
    if (topics == null ||
        topics.topicAnswerList == null ||
        selectIndex < 0 ||
        selectIndex >= topics.topicAnswerList!.length) {
      return null;
    }
    CourseProcessTopicsTopicAnswerList? answerList =
        topics.topicAnswerList?[selectIndex];
    return answerList?.correct != 0;
  }

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

  ///先声测试
  void _voiceXsStart(
      XSVoiceStartEvent event, Emitter<TopicPictureState> emitter) async {
    await audioPlayer.stop();
    // 调用封装好的权限检查和请求方法
    bool result = await requestPermission(
        context, Permission.microphone, "录音", "用于开启录音,识别您的开口作答并给出反馈");
    if (result) {
      methodChannel.invokeMethod('startVoice', {
        'word': event.testWord,
        'type': event.type,
        'userId': event.userId.toString()
      });
      _isRecording = true;
      emitter(XSVoiceTestState());
    }
  }

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

  ///取消评测(用于处理退出页面后录音未停止等异常情况的保护操作)
  void _voiceXsCancel() {
    methodChannel.invokeMethod('cancelVoice');
  }

  ///先声评测结果
  void _voiceXsResult(
      XSVoiceResultEvent event, Emitter<TopicPictureState> emitter) async {
    final Map args = event.message as Map;
    final result = args['result'] as Map;
    final overall = result['overall'].toString();
    int score = int.parse(overall);
    AudioPlayerUtilType audioPlayerUtilType;
    String? lottieFile;
    if (score > 90) {
      audioPlayerUtilType = AudioPlayerUtilType.excellent;
      lottieFile = 'assets/lotties/excellent.zip';
    } else if (score > 70) {
      audioPlayerUtilType = AudioPlayerUtilType.great;
      lottieFile = 'assets/lotties/great.zip';
    } else if (score > 50) {
      audioPlayerUtilType = AudioPlayerUtilType.good;
      lottieFile = 'assets/lotties/good.zip';
    } else {
      audioPlayerUtilType = AudioPlayerUtilType.tryAgain;
    }
    if (lottieFile != null) {
      showCheerRewardDialog(context, lottieFile: lottieFile);
    }
    Log.d("WQF audioPlayerUtilType=$audioPlayerUtilType lottieFile=$lottieFile");
    ClickWithMusicController.instance
        .playMusicAndPerformAction(context, audioPlayerUtilType, () => {
          ///todo 是否需要自动翻页
    });
    // showToast('测评成功,分数是$overall', duration: const Duration(seconds: 5));
    _isRecording = false;
    emitter(XSVoiceTestState());
    if (isLastPage()) {
      showStepPage();
    }
  }

  /// 根据得分计算星星数
  int _evaluateScore(String scoreStr) {
    try {
      int score = int.parse(scoreStr);
      if (score > 80) {
        return 3;
      } else if (score > 60) {
        return 2;
      } else {
        return 1;
      }
    } catch (e) {
      // 如果转换失败,可以返回一个默认值或抛出异常
      print('Error parsing score: $e');
      return 1; // 返回一个默认值表示错误
    }
  }

  // 暂时没用上
  void _voicePlayStateChange(VoicePlayStateChangeEvent event,
      Emitter<TopicPictureState> emitter) async {
    emitter(VoicePlayStateChange());
  }

  // 题目音频播放
  void _questionVoicePlay(
      VoicePlayEvent event, Emitter<TopicPictureState> emitter) async {
    if (_forbiddenWhenCorrect) {
      return;
    }
    _forbiddenWhenCorrect = false;
    await closePlayerResource();
    final topics = _entity?.topics?[_currentPage];
    final urlStr = topics?.audioUrl ?? '';
    await audioPlayer.play(UrlSource(urlStr),
        balance: 0.0, ctx: AudioContext());
  }

  Future<void> closePlayerResource() async {
    if (voicePlayState == VoicePlayState.playing || _isResultSoundPlaying) {
      await audioPlayer.stop();
    }
  }

  ///播放选择结果音效
  void _playResultSound(bool isCorrect) async {
    // await audioPlayer.stop();
    if (audioPlayer.state == PlayerState.playing &&
        _isResultSoundPlaying == false) {
      _voicePlayState = VoicePlayState.stop;
    }
    debugPrint("_playResultSound isCorrect=$isCorrect");
    _isResultSoundPlaying = true;
    _forbiddenWhenCorrect = isCorrect;
    if (isCorrect) {
      await audioPlayer.play(AssetSource('right'.assetMp3));
    } else {
      await audioPlayer.play(AssetSource('wrong'.assetMp3));
    }
  }

  ///是否是最后一页
  bool isLastPage() {
    return currentPage == _entity?.topics?.length;
  }

  ///展示过渡页
  void showStepPage() {
    ///如果最后一页是语音问答题,评测完后自动翻页
    sectionComplete(() {
      popPage(data: {
        'currentStep': currentPage,
        'courseLessonId': courseLessonId,
        'isCompleted': true,
        'nextSection': true
      });
    }, againSectionTap: () {
      pageController.jumpToPage(0);
    });
  }
}