#12 tencent_trtc_cloud 卡麦

Open
opened 1 year ago by lyq · 8 comments
天问 commented 1 year ago

tencent_trtc_cloud 卡麦,开直播的时候,几分钟没声音

tencent_trtc_cloud 卡麦,开直播的时候,几分钟没声音
天问 commented 1 year ago
Owner

写一份服务,在后台运行。

写一份服务,在后台运行。
天问 commented 1 year ago
Owner

1、部分手机,开麦没有声音。

2、掉麦。

app长时间不操作,会掉麦,但不会退出房间。

用户可以听到声音,但是不在麦上,用户无法给其刷钱。 :推出直播间,重新进去就好了

自己在麦上,但是其他用户看不到,导致用户看不到。

1、部分手机,开麦没有声音。 2、掉麦。 app长时间不操作,会掉麦,但不会退出房间。 用户可以听到声音,但是不在麦上,用户无法给其刷钱。 :推出直播间,重新进去就好了 自己在麦上,但是其他用户看不到,导致用户看不到。
天问 commented 1 year ago
Owner

解决方案:

退后台后,开启前台服务(service),或者悬浮框

解决方案: 退后台后,开启前台服务(service),或者悬浮框
天辰 commented 1 year ago
Owner

Base.dart 配置服务器相关信息:

api 服务:

  static const baseSchema = 'https';
  static const baseHost = 'yujian-api.tinger.net.cn';
  static const basePort = '443';

h5, oss:

  static const miniUrl = 'http://s.tinger.net.cn/';
  static List<dynamic> screenGift = [];
  static String cdnUrl = 'https://yujian-cdn.tinger.net.cn';

定义了 语音全局操作:

  static Future<void> destroyTrtcCloud() async {
    print('销毁语音插件');
    VBase.roomId = 0;
    VBase.trtcCloud = null;
    await VBase.trtcCloud?.stopLocalAudio();
    await VBase.trtcCloud?.exitRoom();
    await TRTCCloud.destroySharedInstance();
  }

  LinearGradient headerLinearGradient(){
    return const LinearGradient(
      stops: [0.1, 1],
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      transform: GradientRotation(math.pi / 2),
      colors: VBase.headerBackgroundColor,
    );
  }
Base.dart 配置服务器相关信息: api 服务: ``` static const baseSchema = 'https'; static const baseHost = 'yujian-api.tinger.net.cn'; static const basePort = '443'; ``` h5, oss: ``` static const miniUrl = 'http://s.tinger.net.cn/'; static List<dynamic> screenGift = []; static String cdnUrl = 'https://yujian-cdn.tinger.net.cn'; ``` 定义了 语音全局操作: ``` static Future<void> destroyTrtcCloud() async { print('销毁语音插件'); VBase.roomId = 0; VBase.trtcCloud = null; await VBase.trtcCloud?.stopLocalAudio(); await VBase.trtcCloud?.exitRoom(); await TRTCCloud.destroySharedInstance(); } LinearGradient headerLinearGradient(){ return const LinearGradient( stops: [0.1, 1], begin: Alignment.topLeft, end: Alignment.bottomRight, transform: GradientRotation(math.pi / 2), colors: VBase.headerBackgroundColor, ); } ```
天辰 commented 1 year ago
Owner

service.dart 定义销毁房间:

abstract class VRoom {
  static TRTCCloud? trtcCloud;
  static bool trtcCloudIsActive = false;

  static Future<void> exitRoom(String name) async {
    if (VRoom.trtcCloudIsActive) {
      // VRoom.trtcCloud.unRegisterListener(onTrtcListener);
      await VRoom.trtcCloud?.stopLocalAudio();
      await VRoom.trtcCloud?.exitRoom();
      await TRTCCloud.destroySharedInstance();
      print('销毁房间语音信息');
    }
  }
}
service.dart 定义销毁房间: ``` abstract class VRoom { static TRTCCloud? trtcCloud; static bool trtcCloudIsActive = false; static Future<void> exitRoom(String name) async { if (VRoom.trtcCloudIsActive) { // VRoom.trtcCloud.unRegisterListener(onTrtcListener); await VRoom.trtcCloud?.stopLocalAudio(); await VRoom.trtcCloud?.exitRoom(); await TRTCCloud.destroySharedInstance(); print('销毁房间语音信息'); } } } ```
天辰 commented 1 year ago
Owner

lib\chat\VoiceChatRoomPage.dart 聊天界面

  late TRTCCloud trtcCloud;
  late bool trtcCloudIsActive = false;

  //静音所有用户
  late bool _muteAll = false;

  //静音部份用户
  late List<int> _muteUser = [];
  MethodChannel _channel = const MethodChannel('trtcCloudChannel');


  _changeRole(int role, String privilege) {
    print('变更角色:${VBase.uid}:${TRTCCloudDef.TRTCRoleAnchor}');
    print('privilege:${privilege}');
    if (trtcCloudIsActive) {
      setState(() {
        _roomDetailData.voicePermission = role == TRTCCloudDef.TRTCRoleAnchor ? true : false;
      });
      // var result = _channel.invokeMethod('switchRole', {
      //   "role": role,
      //   "privateMapKey": privilege
      // });
      trtcCloud?.exitRoom();
      TRTCParams params = TRTCParams();
      params.sdkAppId = VBase.sdkAppId;
      params.strRoomId = _roomId.toString();
      params.roomId = _roomId;
      params.userId = VBase.uid.toString();

这里定义了大部分语音操作,

lib\chat\VoiceChatRoomPage.dart 聊天界面 ``` late TRTCCloud trtcCloud; late bool trtcCloudIsActive = false; //静音所有用户 late bool _muteAll = false; //静音部份用户 late List<int> _muteUser = []; MethodChannel _channel = const MethodChannel('trtcCloudChannel'); _changeRole(int role, String privilege) { print('变更角色:${VBase.uid}:${TRTCCloudDef.TRTCRoleAnchor}'); print('privilege:${privilege}'); if (trtcCloudIsActive) { setState(() { _roomDetailData.voicePermission = role == TRTCCloudDef.TRTCRoleAnchor ? true : false; }); // var result = _channel.invokeMethod('switchRole', { // "role": role, // "privateMapKey": privilege // }); trtcCloud?.exitRoom(); TRTCParams params = TRTCParams(); params.sdkAppId = VBase.sdkAppId; params.strRoomId = _roomId.toString(); params.roomId = _roomId; params.userId = VBase.uid.toString(); ``` 这里定义了大部分语音操作,
天问 commented 1 year ago
Owner
参考项目: https://github.com/LiteAVSDK/TRTC_Flutter
天问 commented 1 year ago
Owner

flutter_foreground_task 插件使用:

第一步:增加权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>

<service
    android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
    android:stopWithTask="true" />

权限检测:

///启动前台服务需要一系列的授权
Future<void> _requestPermissionForAndroid() async {
  if (!Platform.isAndroid) {
    return;
  }
  if (!await FlutterForegroundTask.canDrawOverlays) {
    ///打开设置页面,您可以在其中允许拒绝“android.permission.SYSTEM_ALERT_WINDOW”权限。传递“forceOpen”布尔值以打开权限页面,即使已授予。
    await FlutterForegroundTask.openSystemAlertWindowSettings();
  }

  if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) {
    //判断是否开启排除电池优化权限,如果没有开启去开启
    await FlutterForegroundTask.requestIgnoreBatteryOptimization();
  }


  ///检查前台服务权限授予的状态
  final NotificationPermission notificationPermissionStatus =
  await FlutterForegroundTask.checkNotificationPermission();
  if (notificationPermissionStatus != NotificationPermission.granted) {
    //没有授予先去请求
    await FlutterForegroundTask.requestNotificationPermission();
  }
}

第二步 lib\chat\VoiceChatRoomPage.dart 中启动服务:

//初始化这个前台任务
void _initForeground() {
  FlutterForegroundTask.init(
      androidNotificationOptions:
          AndroidNotificationOptions(channelId: 'notification_channel_id', channelName: 'Foreground Notification'),
      iosNotificationOptions: const IOSNotificationOptions(),
      foregroundTaskOptions: const ForegroundTaskOptions());
}

_initForeground 函数中 FlutterForegroundTask.init 初始化一个前台服务,该方法在 initState 启动时调用。

然后一个启动服务函数 _startForegroundTask

  Future<bool> _startForegroundTask() async {
    // You can save data using the saveData function.
    await FlutterForegroundTask.saveData(key: 'customData', value: 'hello');

    // Register the receivePort before starting the service.
    final ReceivePort? receivePort = FlutterForegroundTask.receivePort;
    final bool isRegistered = _registerReceivePort(receivePort);
    if (!isRegistered) {
      print('Failed to register receivePort!');
      return false;
    }

    if (await FlutterForegroundTask.isRunningService) {
      return FlutterForegroundTask.restartService();
    } else {
      return FlutterForegroundTask.startService(
        notificationTitle: '正在运行',
        notificationText: '点击进入房间${_roomDetailData.room.roomName??''}',
        // callback: startCallback,
      );
    }
  }

该函数在隐藏直播间的时候执行,启动服务:

  _handleHiddenRoom() {
    print('隐藏房间:$_roomId');
   if(Platform.isAndroid){
      _startForegroundTask();
   }

结束服务:

  Future<bool> _stopForegroundTask() {
    return FlutterForegroundTask.stopService();
  }

服务回调函数,直播在后台运行,新建MyTaskHandler 继承TaskHandler


flutter_foreground_task 插件使用: 第一步:增加权限 ``` <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/> <service android:name="com.pravera.flutter_foreground_task.service.ForegroundService" android:stopWithTask="true" /> ``` 权限检测: ``` ///启动前台服务需要一系列的授权 Future<void> _requestPermissionForAndroid() async { if (!Platform.isAndroid) { return; } if (!await FlutterForegroundTask.canDrawOverlays) { ///打开设置页面,您可以在其中允许拒绝“android.permission.SYSTEM_ALERT_WINDOW”权限。传递“forceOpen”布尔值以打开权限页面,即使已授予。 await FlutterForegroundTask.openSystemAlertWindowSettings(); } if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) { //判断是否开启排除电池优化权限,如果没有开启去开启 await FlutterForegroundTask.requestIgnoreBatteryOptimization(); } ///检查前台服务权限授予的状态 final NotificationPermission notificationPermissionStatus = await FlutterForegroundTask.checkNotificationPermission(); if (notificationPermissionStatus != NotificationPermission.granted) { //没有授予先去请求 await FlutterForegroundTask.requestNotificationPermission(); } } ``` 第二步 lib\chat\VoiceChatRoomPage.dart 中启动服务: ``` //初始化这个前台任务 void _initForeground() { FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions(channelId: 'notification_channel_id', channelName: 'Foreground Notification'), iosNotificationOptions: const IOSNotificationOptions(), foregroundTaskOptions: const ForegroundTaskOptions()); } ``` **_initForeground** 函数中 FlutterForegroundTask.init 初始化一个前台服务,该方法在 initState 启动时调用。 然后一个启动服务函数 **_startForegroundTask**: ``` Future<bool> _startForegroundTask() async { // You can save data using the saveData function. await FlutterForegroundTask.saveData(key: 'customData', value: 'hello'); // Register the receivePort before starting the service. final ReceivePort? receivePort = FlutterForegroundTask.receivePort; final bool isRegistered = _registerReceivePort(receivePort); if (!isRegistered) { print('Failed to register receivePort!'); return false; } if (await FlutterForegroundTask.isRunningService) { return FlutterForegroundTask.restartService(); } else { return FlutterForegroundTask.startService( notificationTitle: '正在运行', notificationText: '点击进入房间${_roomDetailData.room.roomName??''}', // callback: startCallback, ); } } ``` 该函数在隐藏直播间的时候执行,启动服务: ``` _handleHiddenRoom() { print('隐藏房间:$_roomId'); if(Platform.isAndroid){ _startForegroundTask(); } ``` 结束服务: ``` Future<bool> _stopForegroundTask() { return FlutterForegroundTask.stopService(); } ``` 服务回调函数,直播在后台运行,新建**MyTaskHandler** 继承**TaskHandler** : ``` ```
Sign in to join this conversation.
No Milestone
No assignee
2 Participants
Loading...
Cancel
Save
There is no content yet.