audio_recorder.dart 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:file/local.dart';
  4. import 'package:flutter/services.dart';
  5. import 'package:path/path.dart' as p;
  6. /// Audio Recorder Plugin
  7. class FlutterAudioRecorder {
  8. static const MethodChannel _channel =
  9. MethodChannel('flutter_audio_recorder2');
  10. static const String DEFAULT_EXTENSION = '.m4a';
  11. static LocalFileSystem fs = LocalFileSystem();
  12. String? _path;
  13. String? _extension;
  14. Recording? _recording;
  15. String? _sampleRate;
  16. Future? _initRecorder;
  17. Future? get initialized => _initRecorder;
  18. Recording? get recording => _recording;
  19. /// 构造方法
  20. /// path audio文件路径
  21. FlutterAudioRecorder(String path,
  22. {AudioFormat? audioFormat, String sampleRate = "16000"}) {
  23. _initRecorder = _init(path, audioFormat, sampleRate);
  24. }
  25. /// 初始化 FlutterAudioRecorder 对象
  26. Future _init(
  27. String? path, AudioFormat? audioFormat, String sampleRate) async {
  28. String extension;
  29. String extensionInPath;
  30. if (path != null) {
  31. // Extension(.xyz) of Path
  32. extensionInPath = p.extension(path);
  33. // Use AudioFormat
  34. if (audioFormat != null) {
  35. // .m4a != .m4a
  36. if (_stringToAudioFormat(extensionInPath) != audioFormat) {
  37. // use AudioOutputFormat
  38. extension = _audioFormatToString(audioFormat);
  39. path = p.withoutExtension(path) + extension;
  40. } else {
  41. extension = p.extension(path);
  42. }
  43. } else {
  44. // Else, Use Extension that inferred from Path
  45. // if extension in path is valid
  46. if (_isValidAudioFormat(extensionInPath)) {
  47. extension = extensionInPath;
  48. } else {
  49. extension = DEFAULT_EXTENSION; // default value
  50. path += extension;
  51. }
  52. }
  53. File file = fs.file(path);
  54. if (await file.exists()) {
  55. throw Exception("A file already exists at the path :" + path);
  56. } else if (!await file.parent.exists()) {
  57. throw Exception(
  58. "The specified parent directory does not exist ${file.parent}");
  59. }
  60. } else {
  61. extension = DEFAULT_EXTENSION; // default value
  62. }
  63. _path = path;
  64. _extension = extension;
  65. _sampleRate = sampleRate;
  66. late Map<String, Object> response;
  67. var result = await _channel.invokeMethod('init',
  68. {"path": _path, "extension": _extension, "sampleRate": _sampleRate});
  69. if (result != false) {
  70. response = Map.from(result);
  71. }
  72. _recording = Recording()
  73. ..status = _stringToRecordingStatus(response['status'] as String?)
  74. ..metering = AudioMetering(
  75. averagePower: -120, peakPower: -120, isMeteringEnabled: true);
  76. return;
  77. }
  78. /// Request an initialized recording instance to be [started]
  79. /// Once executed, audio recording will start working and
  80. /// a file will be generated in user's file system
  81. Future start() async {
  82. return _channel.invokeMethod('start');
  83. }
  84. /// Request currently [Recording] recording to be [Paused]
  85. /// Note: Use [current] to get latest state of recording after [pause]
  86. Future pause() async {
  87. return _channel.invokeMethod('pause');
  88. }
  89. /// Request currently [Paused] recording to continue
  90. Future resume() async {
  91. return _channel.invokeMethod('resume');
  92. }
  93. /// Request the recording to stop
  94. /// Once its stopped, the recording file will be finalized
  95. /// and will not be start, resume, pause anymore.
  96. Future<Recording?> stop() async {
  97. Map<String, Object> response;
  98. var result = await _channel.invokeMethod('stop');
  99. if (result != null) {
  100. response = Map.from(result);
  101. _responseToRecording(response);
  102. }
  103. return _recording;
  104. }
  105. /// Ask for current status of recording
  106. /// Returns the result of current recording status
  107. /// Metering level, Duration, Status...
  108. Future<Recording?> current({int channel = 0}) async {
  109. Map<String, Object> response;
  110. var result = await _channel.invokeMethod('current', {"channel": channel});
  111. if (result != null && _recording?.status != RecordingStatus.Stopped) {
  112. response = Map.from(result);
  113. _responseToRecording(response);
  114. }
  115. return _recording;
  116. }
  117. /// Returns the result of record permission
  118. /// if not determined(app first launch),
  119. /// this will ask user to whether grant the permission
  120. static Future<bool?> get hasPermissions async {
  121. bool? hasPermission = await _channel.invokeMethod('hasPermissions');
  122. return hasPermission;
  123. }
  124. /// util - response msg to recording object.
  125. void _responseToRecording(Map<String, Object>? response) {
  126. if (response == null) return;
  127. _recording!.duration = Duration(milliseconds: response['duration'] as int);
  128. _recording!.path = response['path'] as String?;
  129. _recording!.audioFormat =
  130. _stringToAudioFormat(response['audioFormat'] as String?);
  131. _recording!.extension = response['audioFormat'] as String?;
  132. _recording!.metering = AudioMetering(
  133. peakPower: response['peakPower'] as double?,
  134. averagePower: response['averagePower'] as double?,
  135. isMeteringEnabled: response['isMeteringEnabled'] as bool?);
  136. _recording!.status =
  137. _stringToRecordingStatus(response['status'] as String?);
  138. }
  139. /// util - verify if extension string is supported
  140. static bool _isValidAudioFormat(String extension) {
  141. switch (extension) {
  142. case ".wav":
  143. case ".mp4":
  144. case ".aac":
  145. case ".m4a":
  146. return true;
  147. default:
  148. return false;
  149. }
  150. }
  151. /// util - Convert String to Enum
  152. static AudioFormat? _stringToAudioFormat(String? extension) {
  153. switch (extension) {
  154. case ".wav":
  155. return AudioFormat.WAV;
  156. case ".mp4":
  157. case ".aac":
  158. case ".m4a":
  159. return AudioFormat.AAC;
  160. default:
  161. return null;
  162. }
  163. }
  164. /// Convert Enum to String
  165. static String _audioFormatToString(AudioFormat format) {
  166. switch (format) {
  167. case AudioFormat.WAV:
  168. return ".wav";
  169. case AudioFormat.AAC:
  170. return ".m4a";
  171. default:
  172. return ".m4a";
  173. }
  174. }
  175. /// util - Convert String to Enum
  176. static RecordingStatus _stringToRecordingStatus(String? status) {
  177. switch (status) {
  178. case "unset":
  179. return RecordingStatus.Unset;
  180. case "initialized":
  181. return RecordingStatus.Initialized;
  182. case "recording":
  183. return RecordingStatus.Recording;
  184. case "paused":
  185. return RecordingStatus.Paused;
  186. case "stopped":
  187. return RecordingStatus.Stopped;
  188. default:
  189. return RecordingStatus.Unset;
  190. }
  191. }
  192. }
  193. /// Recording Object - represent a recording file
  194. class Recording {
  195. /// File path
  196. String? path;
  197. /// Extension
  198. String? extension;
  199. /// Duration in milliseconds
  200. Duration? duration;
  201. /// Audio format
  202. AudioFormat? audioFormat;
  203. /// Metering
  204. AudioMetering? metering;
  205. /// Is currently recording
  206. RecordingStatus? status;
  207. }
  208. /// Audio Metering Level - describe the metering level of microphone when recording
  209. class AudioMetering {
  210. /// Represent peak level of given short duration
  211. double? peakPower;
  212. /// Represent average level of given short duration
  213. double? averagePower;
  214. /// Is metering enabled in system
  215. bool? isMeteringEnabled;
  216. AudioMetering({this.peakPower, this.averagePower, this.isMeteringEnabled});
  217. }
  218. /// 自定义录音状态
  219. enum RecordingStatus {
  220. /// Recording not initialized
  221. Unset,
  222. /// Ready for start recording
  223. Initialized,
  224. /// Currently recording
  225. Recording,
  226. /// Currently Paused
  227. Paused,
  228. /// This specific recording Stopped, cannot be start again
  229. Stopped,
  230. }
  231. /// Audio Format,
  232. /// WAV is lossless audio, recommended
  233. enum AudioFormat {
  234. AAC,
  235. WAV,
  236. }