repeat_after_content_bloc.dart
10.2 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
import 'dart:io';
import 'dart:async';
import 'package:audio_session/audio_session.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wow_english/common/request/dao/listen_dao.dart';
import '../../../common/request/exception.dart';
import '../../../models/read_content_entity.dart';
import '../../../utils/loading.dart';
import '../../../utils/toast_util.dart';
part 'repeat_after_content_event.dart';
part 'repeat_after_content_state.dart';
enum VoiceRecordState {
///未知
voiceRecordUnkonw,
///开始录音
voiceRecordStat,
///正在录音
voiceRecording,
///录音结束
voiceRecordEnd
}
///先声测评状态
enum XSVoiceCheckState {
///未知
unKnow,
///测评开始
start,
///测评结束
stop,
}
class RepeatAfterContentBloc extends Bloc<RepeatAfterContentEvent, RepeatAfterContentState> {
final String courseLessonId;
/// 是否正在播放视频
bool _videoPlaying = true;
bool get videoPlaying => _videoPlaying;
/// 是否正在录音
bool _isRecord = false;
bool get isRecord => _isRecord;
/// 先声评测状态
XSVoiceCheckState _xSCheckState = XSVoiceCheckState.unKnow;
XSVoiceCheckState get xSCheckState => _xSCheckState;
/// 评测结果
Map? _voiceTestResult;
Map? get voiceTestResult => _voiceTestResult;
/// 录音的次数
int _recordNumber = 0;
/// 录音文件地址
String _path = '';
String get path => _path;
/// 当前播放的视频位置
int _currentPlayIndex = 0;
int get currentPlayIndex => _currentPlayIndex;
/// 录音状态
VoiceRecordState _voiceRecordState = VoiceRecordState.voiceRecordUnkonw;
VoiceRecordState get voiceRecordState => _voiceRecordState;
/// 跟读内容数字
List<ReadContentEntity?>? _entityList;
List<ReadContentEntity?>? get entityList => _entityList ;
/// 方法
late MethodChannel methodChannel;
///录音
late FlutterSoundRecorder _soundRecorder;
late FlutterSoundPlayer _soundPlayer;
StreamSubscription? _soundPlayerListen;
RepeatAfterContentBloc(this.courseLessonId) : super(RepeatAfterContentInitial()) {
on<VoiceRecordStateChangeEvent>(_voiceRecordStateChange);
on<PostFollowReadContentEvent>(_postFollowReadContent);
on<ChangeVideoPlayIndexEvent>(_changeVideoPlayIndex);
on<VideoPlayChangeEvent>(_videoPlayStateChange);
on<RecordeVoicePlayEvent>(_recordeVoicePlay);
on<StarRecordVoiceEvent>(_starRecordVoice);
on<StopRecordVoiceEvent>(_stopRecordVoice);
on<XSVoiceResultEvent>(_voiceXsResult);
on<XSVoiceInitEvent>(_initVoiceSdk);
on<RequestDataEvent>(_requestData);
on<XSVoiceTestEvent>(_voiceXsTest);
on<XSVoiceStopEvent>(_voiceXsStop);
on<VoiceRecordEvent>(_voiceRecord);
on<InitBlocEvent>(_initBlocData);
}
@override
Future<void> close() {
_releaseFlauto();
_voiceXsCancel();
return super.close();
}
///初始化功能
void _initBlocData(InitBlocEvent event, Emitter<RepeatAfterContentState> emitter) async {
methodChannel = const MethodChannel('wow_english/sing_sound_method_channel');
methodChannel.setMethodCallHandler((call) async {
if (call.method == 'voiceResult') {//评测结果
add(XSVoiceResultEvent(call.arguments));
add(PostFollowReadContentEvent());
}
});
//录音
_soundRecorder = FlutterSoundRecorder();
await _soundRecorder.openRecorder();
// await _soundRecorder.setSubscriptionDuration(const Duration(milliseconds: 10));
//音屏
_soundPlayer = FlutterSoundPlayer();
//设置音频
final session = await AudioSession.instance;
await session.configure(AudioSessionConfiguration(
avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
avAudioSessionCategoryOptions:
AVAudioSessionCategoryOptions.allowBluetooth |
AVAudioSessionCategoryOptions.defaultToSpeaker,
avAudioSessionMode: AVAudioSessionMode.spokenAudio,
avAudioSessionRouteSharingPolicy:
AVAudioSessionRouteSharingPolicy.defaultPolicy,
avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
androidAudioAttributes: const AndroidAudioAttributes(
contentType: AndroidAudioContentType.speech,
flags: AndroidAudioFlags.none,
usage: AndroidAudioUsage.voiceCommunication,
),
androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
androidWillPauseWhenDucked: true,
));
await _soundPlayer.closePlayer();
await _soundPlayer.openPlayer();
// await _soundPlayer.setSubscriptionDuration(const Duration(milliseconds: 10));
}
///请求数据
void _requestData(RequestDataEvent event,Emitter<RepeatAfterContentState> emitter) async {
try {
await loading(() async {
_entityList = await ListenDao.readContent(courseLessonId);
emitter(RequestDataState());
});
} catch (e) {
if (e is ApiException) {
showToast(e.message??'请求失败,请检查网络连接');
}
}
}
///跟读结果
void _postFollowReadContent(PostFollowReadContentEvent event,Emitter<RepeatAfterContentState> emitter) async {
try {
await loading(() async {
_entityList = await ListenDao.followResult(_recordNumber.toString(),courseLessonId);
});
} catch (e) {
if (e is ApiException) {
}
}
}
void _videoPlayStateChange(VideoPlayChangeEvent event,Emitter<RepeatAfterContentState> emitter) async {
_videoPlaying = !_videoPlaying;
emitter(VideoPlayChangeState());
}
void _voiceRecord(VoiceRecordEvent event,Emitter<RepeatAfterContentState> emitter) async {
_isRecord = !_isRecord;
emitter(VoiceRecordChangeState());
}
void _voiceRecordStateChange(VoiceRecordStateChangeEvent event,Emitter<RepeatAfterContentState> emitter) async {
_voiceRecordState = event.voiceRecordState;
emitter(VoiceRecordStateChange());
}
_initVoiceSdk(XSVoiceInitEvent event,Emitter<RepeatAfterContentState> emitter) async {
methodChannel.invokeMethod('initVoiceSdk',event.data);
}
///先声测试
void _voiceXsTest(XSVoiceTestEvent event,Emitter<RepeatAfterContentState> emitter) async {
await methodChannel.invokeMethod(
'startLocalVoice',
{
'type':event.type,
'word':event.testWord,
'voicePath':_path,
'userId':event.userId.toString()
}
);
_recordNumber++;
_xSCheckState = XSVoiceCheckState.start;
emitter(XSVoiceTestState());
}
///终止评测
void _voiceXsStop(XSVoiceStopEvent event,Emitter<RepeatAfterContentState> emitter) async {
methodChannel.invokeMethod('stopVoice');
}
///取消评测(用于处理退出页面后录音未停止等异常情况的保护操作)
void _voiceXsCancel() {
methodChannel.invokeMethod('cancelVoice');
}
///先声评测结果
void _voiceXsResult(XSVoiceResultEvent event,Emitter<RepeatAfterContentState> emitter) async {
final Map args = event.message as Map;
final result = args['result'] as Map;
final overall = result['overall'].toString();
_voiceTestResult = {'overall':overall};
emitter(XSVoiceTestState());
}
///播放声音
void _recordeVoicePlay(RecordeVoicePlayEvent event,Emitter<RepeatAfterContentState> emitter) async {
if (await _fileExists(_path)) {
if (_soundPlayer.isPlaying) {
_soundPlayer.stopPlayer();
}
await _soundPlayer.startPlayer(
fromURI: path,
codec: Codec.aacADTS,
sampleRate: 44000,
whenFinished: (){
}
);
}
}
///更改播放的视频
void _changeVideoPlayIndex(ChangeVideoPlayIndexEvent event,Emitter<RepeatAfterContentState> emitter) async {
if (_entityList == null || _entityList!.isEmpty) {
return;
}
if (event.isNext) {
if (_currentPlayIndex < _entityList!.length-1) {
_currentPlayIndex++;
}
} else {
if (_currentPlayIndex >0) {
_currentPlayIndex--;
}
}
emitter(ChangeVideoPlayIndexState(event.isNext));
}
///开始录音
void _starRecordVoice(StarRecordVoiceEvent event,Emitter<RepeatAfterContentState> emitter) async {
try {
await getPermissionStatus().then((value) async {
if (!value) {
debugPrint('失败$value');
return;
}
Directory tempDir = await getTemporaryDirectory();
var time = DateTime.now().millisecondsSinceEpoch;
String path = '${tempDir.path}/$time${ext[Codec.aacADTS.index]}';
_path = path;
debugPrint('=====> 准备开始录音');
await _soundRecorder.startRecorder(
toFile: path,
codec: Codec.aacADTS,
bitRate: 8000,
numChannels: 1,
sampleRate: 8000,
);
debugPrint('=====> 开始录音');
_voiceRecordState = VoiceRecordState.voiceRecording;
emitter(VoiceRecordStateChange());
});
} catch (error) {
await _soundRecorder.stopRecorder();
}
}
///停止录音
void _stopRecordVoice(StopRecordVoiceEvent event,Emitter<RepeatAfterContentState> emitter) async {
debugPrint('=====> 停止录音');
await _soundRecorder.stopRecorder();
_voiceRecordState = VoiceRecordState.voiceRecordEnd;
emitter(VoiceRecordStateChange());
}
/// 判断文件是否存在
Future<bool> _fileExists(String path) async {
return await File(path).exists();
}
///获取权限
Future<bool> getPermissionStatus() async {
Permission permission = Permission.microphone;
PermissionStatus status = await permission.status;
if (status.isGranted) {
return true;
} else if (status.isDenied) {
requestPermission(permission);
} else if (status.isPermanentlyDenied) {
openAppSettings();
} else if (status.isRestricted) {
requestPermission(permission);
} else {
}
return false;
}
/// 释放录音
Future<void> _releaseFlauto() async {
await _soundRecorder.closeRecorder();
}
///申请权限
void requestPermission(Permission permission) async {
PermissionStatus status = await permission.request();
if (status.isPermanentlyDenied) {
openAppSettings();
}
}
}