Flutter实时音视频通信插件agora_rtc_engine的使用
Flutter实时音视频通信插件agora_rtc_engine的使用
简介
agora_rtc_engine
是一个Flutter插件,用于集成Agora Video SDK。它允许开发者通过简单的API将实时语音和视频通信功能添加到自己的应用程序中。以下是关于如何使用该插件的一些详细信息。
使用方法
添加依赖
要在项目中使用此插件,请在项目的 pubspec.yaml
文件中添加 agora_rtc_engine
作为依赖项:
dependencies:
agora_rtc_engine: ^6.0.0 # 请根据实际需要选择版本号
获取开始
您可以从 example 文件夹获取一些基本和高级示例代码。
隐私权限
Agora Video SDK 需要 Camera
和 Microphone
权限以启动视频通话。
Android
确保在 AndroidManifest.xml
文件中添加以下权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- The Agora SDK requires Bluetooth permissions in case users are using Bluetooth devices. -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- For Android 12 and above devices, the following permission is also required. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
更多权限设置请参考官方文档:Android权限设置
iOS & macOS
打开 Info.plist
并添加:
Privacy - Microphone Usage Description
Privacy - Camera Usage Description
更多权限设置请参考官方文档:iOS权限设置
Web (alpha)
Web端支持目前处于alpha阶段,具体配置请参见官方说明。
示例代码
下面是一个简单的例子,展示了如何初始化Agora引擎并加入频道进行视频通话。
import 'dart:async';
import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
const appId = "<-- Insert App Id -->";
const token = "<-- Insert Token -->";
const channel = "<-- Insert Channel Name -->";
void main() => runApp(const MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int? _remoteUid;
bool _localUserJoined = false;
late RtcEngine _engine;
@override
void initState() {
super.initState();
initAgora();
}
Future<void> initAgora() async {
// retrieve permissions
await [Permission.microphone, Permission.camera].request();
//create the engine
_engine = createAgoraRtcEngine();
await _engine.initialize(const RtcEngineContext(
appId: appId,
channelProfile: ChannelProfileType.channelProfileLiveBroadcasting,
));
_engine.registerEventHandler(
RtcEngineEventHandler(
onJoinChannelSuccess: (RtcConnection connection, int elapsed) {
debugPrint("local user ${connection.localUid} joined");
setState(() {
_localUserJoined = true;
});
},
onUserJoined: (RtcConnection connection, int remoteUid, int elapsed) {
debugPrint("remote user $remoteUid joined");
setState(() {
_remoteUid = remoteUid;
});
},
onUserOffline: (RtcConnection connection, int remoteUid,
UserOfflineReasonType reason) {
debugPrint("remote user $remoteUid left channel");
setState(() {
_remoteUid = null;
});
},
onTokenPrivilegeWillExpire: (RtcConnection connection, String token) {
debugPrint(
'[onTokenPrivilegeWillExpire] connection: ${connection.toJson()}, token: $token');
},
),
);
await _engine.setClientRole(role: ClientRoleType.clientRoleBroadcaster);
await _engine.enableVideo();
await _engine.startPreview();
await _engine.joinChannel(
token: token,
channelId: channel,
uid: 0,
options: const ChannelMediaOptions(),
);
}
@override
void dispose() {
super.dispose();
_dispose();
}
Future<void> _dispose() async {
await _engine.leaveChannel();
await _engine.release();
}
// Create UI with local view and remote view
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Agora Video Call'),
),
body: Stack(
children: [
Center(
child: _remoteVideo(),
),
Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 100,
height: 150,
child: Center(
child: _localUserJoined
? AgoraVideoView(
controller: VideoViewController(
rtcEngine: _engine,
canvas: const VideoCanvas(uid: 0),
),
)
: const CircularProgressIndicator(),
),
),
),
],
),
);
}
// Display remote user's video
Widget _remoteVideo() {
if (_remoteUid != null) {
return AgoraVideoView(
controller: VideoViewController.remote(
rtcEngine: _engine,
canvas: VideoCanvas(uid: _remoteUid),
connection: const RtcConnection(channelId: channel),
),
);
} else {
return const Text(
'Please wait for remote user to join',
textAlign: TextAlign.center,
);
}
}
}
以上代码实现了一个简单的视频通话应用,用户可以加入指定频道并与其他用户进行视频通话。需要注意的是,在实际使用时应替换 <-- Insert App Id -->
、<-- Insert Token -->
和 <-- Insert Channel Name -->
为您的实际值。
更多示例代码可以参考:GitHub上的完整示例
API 参考资源
反馈与贡献
如果您有任何问题或建议,请提交 issue 或者拉取请求。有关如何贡献的信息,请参阅 CONTRIBUTING.md。
相关资源
许可证
本项目采用 MIT 许可证。
更多关于Flutter实时音视频通信插件agora_rtc_engine的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter实时音视频通信插件agora_rtc_engine的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用agora_rtc_engine
插件来实现实时音视频通信的示例代码。这个示例将涵盖基本的初始化、加入频道、离开频道以及音视频通信的基本功能。
首先,确保你已经在pubspec.yaml
文件中添加了agora_rtc_engine
依赖:
dependencies:
flutter:
sdk: flutter
agora_rtc_engine: ^x.y.z # 请替换为最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,在你的Flutter项目中,创建一个新的Dart文件(例如agora_service.dart
)来封装Agora RTC Engine的逻辑。
// agora_service.dart
import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/material.dart';
class AgoraService {
late RtcEngine _engine;
late String _channelName;
late String _appId;
late String _token;
late bool _isJoined;
AgoraService({required String appId, required String channelName, String? token}) {
_appId = appId;
_channelName = channelName;
_token = token ?? "";
_isJoined = false;
_initEngine();
}
void _initEngine() {
_engine = RtcEngine.create(_appId);
_engine.setEventHandler(RtcEngineEventHandler()
..onJoinChannelSuccess = (String channel, int uid, int elapsed) {
print("Joined channel: $channel, uid: $uid");
_isJoined = true;
}
..onLeaveChannel = (RtcStats stats) {
print("Left channel");
_isJoined = false;
}
..onError = (int errCode, String errMsg) {
print("Error: $errCode, $errMsg");
}
// 可以添加更多事件处理函数
);
_engine.enableVideo();
_engine.enableAudio();
}
Future<void> joinChannel() async {
if (!_isJoined) {
await _engine.joinChannel(_token, _channelName, null, 0);
}
}
Future<void> leaveChannel() async {
if (_isJoined) {
await _engine.leaveChannel();
}
}
void destroy() {
_engine.destroy();
}
}
然后,在你的主页面(例如main.dart
)中使用这个服务:
// main.dart
import 'package:flutter/material.dart';
import 'agora_service.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Agora RTC Demo'),
),
body: AgoraScreen(),
),
);
}
}
class AgoraScreen extends StatefulWidget {
@override
_AgoraScreenState createState() => _AgoraScreenState();
}
class _AgoraScreenState extends State<AgoraScreen> {
late AgoraService _agoraService;
@override
void initState() {
super.initState();
_agoraService = AgoraService(appId: 'YOUR_APP_ID', channelName: 'test_channel');
}
@override
void dispose() {
_agoraService.destroy();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () async {
await _agoraService.joinChannel();
},
child: Text('Join Channel'),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
await _agoraService.leaveChannel();
},
child: Text('Leave Channel'),
),
],
),
);
}
}
请注意:
- 替换
YOUR_APP_ID
为你的Agora App ID。 - 你可以根据需要添加更多的Agora RTC Engine配置和事件处理。
- 这是一个基本的示例,实际项目中可能需要处理更多的错误和状态管理。
这个示例展示了如何在Flutter中使用agora_rtc_engine
插件进行基本的实时音视频通信。你可以根据需求进一步扩展和定制。