flutter插件:录制系统播放的声音-插件代码

时间:2024-11-16 08:44:41

接下来使用 android studio 打开 system_audio_recorder,编写插件代码。

首先配置一下 system_audio_recorder/pubspec.yaml,添加dependencies

dependencies:  
  flutter:  
    sdk: flutter  
  plugin_platform_interface: ^2.0.2 
  # 新添加的dependencies
  flutter_foreground_task: ^6.0.0+1  
  meta: ^1.5.0

system_audio_recorder/lib 中有三个 dart 文件,三个文件的内容为

system_audio_recorder/lib/system_audio_recorder.dart

  
import 'dart:ffi';  
import 'dart:io';  
  
import 'package:flutter/foundation.dart';  
  
import 'system_audio_recorder_platform_interface.dart';  
import 'package:flutter_foreground_task/flutter_foreground_task.dart';  
  
class SystemAudioRecorder {  
  Future<String?> getPlatformVersion() {  
    return SystemAudioRecorderPlatform.instance.getPlatformVersion();  
  }  
  static Future<bool> startRecord(String name, {String? titleNotification, String? messageNotification, int? sampleRate}) async {  
    try {  
      if (titleNotification == null) {  
        titleNotification = "";  
      }  
      if (messageNotification == null) {  
        messageNotification = "";  
      }  
  
      if (sampleRate == null){  
        sampleRate = 44100;  
      }  
      await _maybeStartFGS(titleNotification, messageNotification);  
      final bool start = await SystemAudioRecorderPlatform.instance.startRecord(  
        name,  
        notificationTitle: titleNotification,  
        notificationMessage: messageNotification,  
        sampleRate: sampleRate,  
      );  
  
      return start;  
    } catch (err) {  
      print("startRecord err");  
      print(err);  
    }  
  
    return false;  
  }  
  
  static Future<String> get stopRecord async {  
    try {  
      final String path = await SystemAudioRecorderPlatform.instance.stopRecord;  
      if (!kIsWeb && Platform.isAndroid) {  
        FlutterForegroundTask.stopService();  
      }  
      return path;  
    } catch (err) {  
      print("stopRecord err");  
      print(err);  
    }  
    return "";  
  }  
  
  static _maybeStartFGS(String titleNotification, String messageNotification) {  
    try {  
      if (!kIsWeb && Platform.isAndroid) {  
        FlutterForegroundTask.init(  
          androidNotificationOptions: AndroidNotificationOptions(  
            channelId: 'notification_channel_id',  
            channelName: titleNotification,  
            channelDescription: messageNotification,  
            channelImportance: NotificationChannelImportance.LOW,  
            priority: NotificationPriority.LOW,  
            iconData: const NotificationIconData(  
              resType: ResourceType.mipmap,  
              resPrefix: ResourcePrefix.ic,  
              name: 'launcher',  
            ),  
          ),  
          iosNotificationOptions: const IOSNotificationOptions(  
            showNotification: true,  
            playSound: false,  
          ),  
          foregroundTaskOptions: const ForegroundTaskOptions(  
            interval: 5000,  
            autoRunOnBoot: true,  
            allowWifiLock: true,  
          ),  
        );  
      }  
    } catch (err) {  
      print("_maybeStartFGS err");  
      print(err);  
    }  
  }  
}

system_audio_recorder_method_channel.dart

import 'package:flutter/foundation.dart';  
import 'package:flutter/services.dart';  
  
import 'system_audio_recorder_platform_interface.dart';  
  
/// An implementation of [SystemAudioRecorderPlatform] that uses method channels.  
class MethodChannelSystemAudioRecorder extends SystemAudioRecorderPlatform {  
  /// The method channel used to interact with the native platform.  
    
  final methodChannel = const MethodChannel('system_audio_recorder');  
  
    
  Future<String?> getPlatformVersion() async {  
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');  
    return version;  
  }  
  
  Future<bool> startRecord(  
      String name, {  
        String notificationTitle = "",  
        String notificationMessage = "",  
        int sampleRate = 44100  
      }) async {  
    final bool start = await methodChannel.invokeMethod('startRecord', {  
      "name": name,  
      "title": notificationTitle,  
      "message": notificationMessage,  
      "sampleRate": sampleRate  
    });  
    return start;  
  }  
  
  
  Future<String> get stopRecord async {  
    final String path = await methodChannel.invokeMethod('stopRecord');  
    return path;  
  }  
}

system_audio_recorder_platform_interface.dart

import 'package:plugin_platform_interface/plugin_platform_interface.dart';  
  
import 'system_audio_recorder_method_channel.dart';  
  
abstract class SystemAudioRecorderPlatform extends PlatformInterface {  
  /// Constructs a SystemAudioRecorderPlatform.  
  SystemAudioRecorderPlatform() : super(token: _token);  
  
  static final Object _token = Object();  
  
  static SystemAudioRecorderPlatform _instance = MethodChannelSystemAudioRecorder();  
  
  /// The default instance of [SystemAudioRecorderPlatform] to use.  
  ///  /// Defaults to [MethodChannelSystemAudioRecorder].  
  static SystemAudioRecorderPlatform get instance => _instance;  
  
  /// Platform-specific implementations should set this with their own  
  /// platform-specific class that extends [SystemAudioRecorderPlatform] when  
  /// they register themselves.  
  static set instance(SystemAudioRecorderPlatform instance) {  
    PlatformInterface.verifyToken(instance, _token);  
    _instance = instance;  
  }  
  
  Future<String?> getPlatformVersion() {  
    throw UnimplementedError('platformVersion() has not been implemented.');  
  }  
  Future<bool> startRecord(  
      String name, {  
        String notificationTitle = "",  
        String notificationMessage = "",  
        int sampleRate = 44100  
      }) {  
    throw UnimplementedError();  
  }  
  
  Future<String> get stopRecord {  
    throw UnimplementedError();  
  }  
}