record_handler.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'dart:typed_data';
  4. import 'package:custom_notification/custom_notification.dart';
  5. import 'package:electronic_assistant/dialog/loading_dialog.dart';
  6. import 'package:electronic_assistant/module/record/record_task.dart';
  7. import 'package:electronic_assistant/resource/colors.gen.dart';
  8. import 'package:electronic_assistant/router/app_pages.dart';
  9. import 'package:flutter/cupertino.dart';
  10. import 'package:flutter_screenutil/flutter_screenutil.dart';
  11. import 'package:flutter_sound/flutter_sound.dart';
  12. import 'package:flutter_sound/public/flutter_sound_recorder.dart';
  13. import 'package:get/get.dart';
  14. import 'package:path_provider/path_provider.dart';
  15. import 'package:flutter_foreground_task/flutter_foreground_task.dart';
  16. import 'package:get/get_rx/src/rx_types/rx_types.dart';
  17. import 'package:permission_handler/permission_handler.dart';
  18. import 'package:uuid/uuid.dart';
  19. import 'package:wakelock_plus/wakelock_plus.dart';
  20. import '../../data/bean/talks.dart';
  21. import '../../data/consts/error_code.dart';
  22. import '../../data/consts/event_report_id.dart';
  23. import '../../data/repositories/talk_repository.dart';
  24. import '../../dialog/alert_dialog.dart';
  25. import '../../dialog/record_max_dialog.dart';
  26. import '../../resource/string.gen.dart';
  27. import '../../utils/http_handler.dart';
  28. import '../../utils/mmkv_util.dart';
  29. import '../../utils/notification_util.dart';
  30. import '../../utils/pcm_wav_converter.dart';
  31. import '../../utils/toast_util.dart';
  32. import '../talk/view.dart';
  33. import 'constants.dart';
  34. class RecordHandler {
  35. RecordHandler._();
  36. static const int minRecordDuration = 3;
  37. static const String recordDone = 'done';
  38. static const String recordPause = 'pause';
  39. static const String recordRecording = 'recording';
  40. static const String keyLastRecordId = "last_record_id";
  41. final Rx<RecordStatus> currentStatus = RecordStatus.pending.obs;
  42. final RxDouble currentDuration = 0.0.obs;
  43. final FlutterSoundRecorder _soundPlayer = FlutterSoundRecorder();
  44. StreamController<Uint8List>? recordingDataController;
  45. static final RecordConfig recordConfig = RecordConfig(
  46. codec: Codec.pcm16,
  47. sampleRate: SampleRate.rate24k.value,
  48. numChannels: Channel.mono.value,
  49. );
  50. StreamSubscription? _recorderSubscription;
  51. bool? _isSoundInited;
  52. String? _lastRecordId;
  53. final int _serviceId = 256;
  54. final String _channelId = StringName.recordNotificationChannelId.tr;
  55. final String _channelName = StringName.recordNotificationChannelName.tr;
  56. String get lastRecordId => _lastRecordId ?? '';
  57. StreamSubscription? _currentDurationListener;
  58. StreamSubscription? _recordActionListener;
  59. final int maxRecordDuration = 60 * 60 * 5; //最大录音时长5小时
  60. final int maxRecordSize = 1024 * 1024 * 1024; //最大录音文件1G
  61. int currentRecordSize = 0;
  62. void init() {
  63. if (currentStatus.value != RecordStatus.recording) {
  64. _initLastRecordId();
  65. _initLastRecordStatus();
  66. _initForegroundService();
  67. _initRecordDurationStream();
  68. }
  69. }
  70. void _initRecordDurationStream() {
  71. _currentDurationListener?.cancel();
  72. _currentDurationListener = currentDuration.listen((event) async {
  73. if (currentStatus.value == RecordStatus.pending ||
  74. !await FlutterForegroundTask.isRunningService) {
  75. return;
  76. }
  77. NotificationUtil.showRecordNotification(
  78. _serviceId, currentStatus.value == RecordStatus.recording, event,
  79. channelId: _channelId, channelName: _channelName);
  80. });
  81. _recordActionListener?.cancel();
  82. _recordActionListener =
  83. CustomNotification.recordActionStream().listen((action) {
  84. if (action == recordDone) {
  85. _recordNotificationDone();
  86. } else if (action == recordPause) {
  87. stopRecord();
  88. } else if (action == recordRecording) {
  89. startOrContinueRecord();
  90. }
  91. });
  92. }
  93. void _recordNotificationDone() {
  94. saveCurrentRecord().then((talkInfo) {
  95. if (Get.currentRoute == RoutePath.record) {
  96. Get.back();
  97. }
  98. TalkPage.start(talkInfo, eventTag: EventId.id_001);
  99. }).catchError((error) {
  100. if (error is ServerErrorException) {
  101. if (error.code == ErrorCode.errorCodeNoLogin) {
  102. ToastUtil.showToast("录音已保存,请登录");
  103. } else {
  104. ToastUtil.showToast("${error.message}");
  105. }
  106. } else {
  107. ToastUtil.showToast("录音已保存,请检查网络并重试");
  108. }
  109. });
  110. }
  111. void _initLastRecordId() {
  112. String? lastRecordId = KVUtil.getString(keyLastRecordId, null);
  113. if (lastRecordId == null || lastRecordId.isEmpty) {
  114. _lastRecordId = const Uuid().v4();
  115. KVUtil.putString(keyLastRecordId, _lastRecordId);
  116. } else {
  117. _lastRecordId = lastRecordId;
  118. }
  119. }
  120. Future<void> _initLastRecordStatus() async {
  121. var currentRecordFile = await _getCurrentRecordFile();
  122. var fileLength = currentRecordFile.lengthSync();
  123. if (currentRecordFile.existsSync() && fileLength > 0) {
  124. _changeRecordStatus(RecordStatus.paused);
  125. double time = _getPcmDuration(
  126. fileLength, recordConfig.sampleRate, 16, recordConfig.numChannels);
  127. currentDuration.value = time;
  128. currentRecordSize = fileLength;
  129. } else {
  130. currentDuration.value = 0;
  131. currentRecordSize = 0;
  132. }
  133. }
  134. double _getPcmDuration(
  135. int fileSize, int sampleRate, int bitDepth, int channels) {
  136. final bytesPerSecond = sampleRate * (bitDepth / 8) * channels;
  137. final durationInSeconds = fileSize / bytesPerSecond;
  138. return durationInSeconds;
  139. }
  140. Future<File> _getCurrentRecordFile() async {
  141. Directory documentDir = await getApplicationDocumentsDirectory();
  142. File file = File("${documentDir.path}/.atmob/record/$_lastRecordId");
  143. if (!file.existsSync()) {
  144. file.createSync(recursive: true);
  145. }
  146. return file;
  147. }
  148. Future<void> stopRecord({bool? isStopService}) async {
  149. _releaseWakeLock();
  150. if (_soundPlayer.isRecording) {
  151. await _soundPlayer.pauseRecorder();
  152. }
  153. _changeRecordStatus(RecordStatus.paused);
  154. if (isStopService == true) {
  155. await FlutterForegroundTask.stopService();
  156. }
  157. }
  158. void _changeRecordStatus(RecordStatus status) async {
  159. currentStatus.value = status;
  160. if (status == RecordStatus.pending ||
  161. !await FlutterForegroundTask.isRunningService) {
  162. return;
  163. }
  164. NotificationUtil.showRecordNotification(
  165. _serviceId, status == RecordStatus.recording, currentDuration.value,
  166. channelId: _channelId, channelName: _channelName);
  167. }
  168. void _setWakeLock() {
  169. WakelockPlus.enable();
  170. }
  171. void _releaseWakeLock() {
  172. WakelockPlus.disable();
  173. }
  174. _initForegroundService() {
  175. WidgetsBinding.instance
  176. .addPostFrameCallback((_) => FlutterForegroundTask.init(
  177. androidNotificationOptions: AndroidNotificationOptions(
  178. channelId: _channelId,
  179. channelName: _channelName,
  180. channelDescription:
  181. StringName.recordNotificationChannelDescription.tr,
  182. channelImportance: NotificationChannelImportance.LOW,
  183. priority: NotificationPriority.LOW,
  184. ),
  185. iosNotificationOptions: const IOSNotificationOptions(
  186. showNotification: false,
  187. playSound: false,
  188. ),
  189. foregroundTaskOptions: ForegroundTaskOptions(
  190. eventAction: ForegroundTaskEventAction.once(),
  191. autoRunOnBoot: false,
  192. autoRunOnMyPackageReplaced: true,
  193. allowWakeLock: true,
  194. allowWifiLock: false,
  195. ),
  196. ));
  197. }
  198. _onRecordPermissionDenied() {
  199. ToastUtil.showToast("需要授予录音权限才能使用录音功能");
  200. }
  201. Future<bool> _showRequestPermissionDialog() async {
  202. bool? isAllow = await EAAlertDialog.show(
  203. contentWidget: Container(
  204. margin: EdgeInsets.only(top: 16.h),
  205. child: Text(
  206. textAlign: TextAlign.center,
  207. '是否允许小听获取此设备的麦克风权限,为您提供转文字、智能总结服务?',
  208. style: TextStyle(
  209. fontWeight: FontWeight.bold,
  210. fontSize: 15.sp,
  211. color: ColorName.primaryTextColor),
  212. ),
  213. ),
  214. cancelText: '禁止',
  215. confirmText: '允许',
  216. cancelOnTap: () {
  217. EAAlertDialog.dismiss(result: false);
  218. },
  219. confirmOnTap: () {
  220. EAAlertDialog.dismiss(result: true);
  221. });
  222. return isAllow ?? false;
  223. }
  224. Future<void> startOrContinueRecord() async {
  225. var isGranted = await Permission.microphone.status;
  226. if (isGranted == PermissionStatus.granted) {
  227. await Permission.microphone.request();
  228. } else {
  229. bool isAllow = await _showRequestPermissionDialog();
  230. if (isAllow) {
  231. var status = await Permission.microphone.request();
  232. if (status != PermissionStatus.granted) {
  233. _onRecordPermissionDenied();
  234. return;
  235. }
  236. } else {
  237. _onRecordPermissionDenied();
  238. return;
  239. }
  240. }
  241. await _requestForegroundTaskPermission().catchError((error) {
  242. debugPrint("requestForegroundTaskPermission error: $error");
  243. });
  244. recordingDataController = StreamController<Uint8List>();
  245. File targetFile = await _getCurrentRecordFile();
  246. if (_recorderSubscription != null) {
  247. _recorderSubscription?.cancel();
  248. }
  249. _recorderSubscription = recordingDataController!.stream.listen((data) {
  250. if (data.isEmpty) {
  251. return;
  252. }
  253. var nowTime = _getPcmDuration(
  254. data.length, recordConfig.sampleRate, 16, recordConfig.numChannels);
  255. if (currentDuration.value + nowTime >= maxRecordDuration) {
  256. showRecordMaxDialog("录音时长已达上限", tag: "recordMaxDialog");
  257. stopRecord();
  258. return;
  259. }
  260. if (currentRecordSize + data.length >= maxRecordSize) {
  261. showRecordMaxDialog("录音文件大小已达上限", tag: "recordMaxDialog");
  262. stopRecord();
  263. return;
  264. }
  265. targetFile.writeAsBytesSync(data, mode: FileMode.append);
  266. currentRecordSize += data.length;
  267. currentDuration.value = currentDuration.value + nowTime;
  268. }, onDone: () {
  269. _changeRecordStatus(RecordStatus.paused);
  270. }, onError: (error) {
  271. _changeRecordStatus(RecordStatus.paused);
  272. });
  273. await _soundPlayer.openRecorder();
  274. _isSoundInited = true;
  275. await _soundPlayer.startRecorder(
  276. toStream: recordingDataController!.sink,
  277. codec: recordConfig.codec,
  278. numChannels: recordConfig.numChannels,
  279. sampleRate: recordConfig.sampleRate);
  280. _setWakeLock();
  281. _startForegroundService();
  282. if (currentStatus.value != RecordStatus.recording) {
  283. _changeRecordStatus(RecordStatus.recording);
  284. }
  285. }
  286. Future<void> _requestForegroundTaskPermission() async {
  287. final NotificationPermission notificationPermission =
  288. await FlutterForegroundTask.checkNotificationPermission();
  289. if (notificationPermission != NotificationPermission.granted) {
  290. await FlutterForegroundTask.requestNotificationPermission();
  291. }
  292. if (Platform.isAndroid) {
  293. if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) {
  294. // This function requires `android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` permission.
  295. await FlutterForegroundTask.requestIgnoreBatteryOptimization();
  296. }
  297. }
  298. }
  299. Future<void> deleteCurrentRecord() async {
  300. await stopRecord(isStopService: true);
  301. File file = await _getCurrentRecordFile();
  302. if (file.existsSync()) {
  303. file.deleteSync();
  304. }
  305. KVUtil.putString(keyLastRecordId, "");
  306. _changeRecordStatus(RecordStatus.pending);
  307. currentDuration.value = 0;
  308. currentRecordSize = 0;
  309. }
  310. Future<void> _startForegroundService() async {
  311. final isRunningService = await FlutterForegroundTask.isRunningService;
  312. if (isRunningService) {
  313. return;
  314. }
  315. await FlutterForegroundTask.startService(
  316. serviceId: _serviceId,
  317. notificationTitle: StringName.appName.tr,
  318. notificationText: StringName.recordStatusRecording.tr,
  319. notificationIcon: null,
  320. notificationButtons: [],
  321. callback: setRecordCallback,
  322. );
  323. }
  324. void releaseSoundRecorder() {
  325. if (_isSoundInited == true) {
  326. _soundPlayer.closeRecorder();
  327. _isSoundInited = false;
  328. }
  329. }
  330. void _cancelRecorderSubscriptions() {
  331. recordingDataController = null;
  332. _recorderSubscription?.cancel();
  333. }
  334. Future<void> getConvertWavFile(String talkId) async {
  335. File pcmFile = await _getCurrentRecordFile();
  336. if (pcmFile.existsSync()) {
  337. File wavFile = await getRecordFile(talkId);
  338. try {
  339. LoadingDialog.show('正在保存录音,请稍等...');
  340. await PcmWavConverter.convert(pcmFile, wavFile, recordConfig.sampleRate,
  341. recordConfig.numChannels, 16);
  342. } catch (e) {
  343. LoadingDialog.hide();
  344. throw ServerErrorException(-1, '录音文件保存失败');
  345. } finally {
  346. LoadingDialog.hide();
  347. }
  348. //检查pcm文件是否可删除
  349. await checkRecordSourceCanDelete(pcmFile, wavFile);
  350. } else {
  351. throw ServerErrorException(-1, "录音文件不存在");
  352. }
  353. }
  354. Future<void> checkRecordSourceCanDelete(File pcmFile, File wavFile) async {
  355. if (!pcmFile.existsSync() || !wavFile.existsSync()) {
  356. throw ServerErrorException(-1, "录音文件不存在");
  357. }
  358. int wavFileLength = wavFile.lengthSync();
  359. if (wavFileLength <= 44) {
  360. throw ServerErrorException(-1, "录音文件异常");
  361. }
  362. if (wavFileLength < pcmFile.lengthSync()) {
  363. throw ServerErrorException(-1, "录音文件未转换成功");
  364. }
  365. pcmFile.delete();
  366. KVUtil.putString(keyLastRecordId, "");
  367. }
  368. Future<TalkBean> saveCurrentRecord() async {
  369. final currentDurationValue = currentDuration.value;
  370. if (currentDurationValue < minRecordDuration) {
  371. throw ServerErrorException(-1, "录音时长不足$minRecordDuration秒");
  372. }
  373. await recordHandler.stopRecord(isStopService: true);
  374. //检查录音文件
  375. if (!await checkRecordFile()) {
  376. throw ServerErrorException(-1, "录音文件不存在");
  377. }
  378. return talkRepository
  379. .talkCreate(recordHandler.lastRecordId, currentDuration.value.toInt())
  380. .then((talkInfo) async {
  381. await recordHandler.getConvertWavFile(talkInfo.id);
  382. return talkInfo;
  383. });
  384. }
  385. Future<bool> checkRecordFile() async {
  386. File pcmFile = await _getCurrentRecordFile();
  387. if (pcmFile.existsSync()) {
  388. return true;
  389. }
  390. return false;
  391. }
  392. void onClose() async {
  393. if (currentStatus.value != RecordStatus.recording) {
  394. releaseSoundRecorder();
  395. _cancelRecorderSubscriptions();
  396. }
  397. }
  398. //********************静态方法***************************/
  399. /// 判断是否有未上传的录音
  400. static Future<bool> hasUnUploadRecord() async {
  401. String? lastRecordId = KVUtil.getString(keyLastRecordId, null);
  402. if (lastRecordId == null || lastRecordId.isEmpty) {
  403. return false;
  404. }
  405. Directory documentDir = await getApplicationDocumentsDirectory();
  406. File file = File("${documentDir.path}/.atmob/record/$lastRecordId");
  407. return await file.exists() && await file.length() > 0;
  408. }
  409. /// 获取录音文件地址
  410. static Future<File> getRecordFile(String talkId) async {
  411. Directory documentDir = await getApplicationDocumentsDirectory();
  412. return File("${documentDir.path}/.atmob/record/$talkId.wav");
  413. }
  414. static Future<File> getPcmRecordFile(String requestId) async {
  415. Directory documentDir = await getApplicationDocumentsDirectory();
  416. return File("${documentDir.path}/.atmob/record/$requestId");
  417. }
  418. }
  419. class RecordConfig {
  420. Codec codec;
  421. int numChannels;
  422. int sampleRate;
  423. RecordConfig(
  424. {required this.codec,
  425. required this.numChannels,
  426. required this.sampleRate});
  427. }
  428. final recordHandler = RecordHandler._();