Flutter视频广播插件ivs_broadcaster的使用

发布于 1周前 作者 eggper 来自 Flutter

Flutter视频广播插件ivs_broadcaster的使用

ivs_broadcaster 是一个为Flutter设计的包,用于通过AWS Interactive Video Service (IVS)进行实时视频广播和播放流媒体。它支持在Android和iOS平台上进行视频流的广播和播放。

目录

开始

要使用此包,您需要拥有一个设置了IVS频道的AWS账户。请按照以下说明完成Android和iOS平台的设置。

设置

Android设置

  1. 在您的AndroidManifest.xml文件中添加以下权限:
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    
  2. 使用您的IVS频道URL和流密钥初始化广播器:
    String imgset = 'rtmp://<your channel url>';
    String streamKey = '<your stream key>';
    

iOS设置

  1. 在您的Info.plist文件中添加以下键:
    <key>NSCameraUsageDescription</key>
    <string>To stream video</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>To stream the audio</string>
    

使用方法

广播器

为了使用广播器,请初始化它并将BroadcaterPreview添加到您的小部件树中:

import 'package:ivs_broadcaster/ivs_broadcaster.dart';

IvsBroadcaster? ivsBroadcaster;

@override
void initState() {
  super.initState();
  ivsBroadcaster = IvsBroadcaster.instance;
}

// 在您的小部件树中
child: BroadcaterPreview(),

播放器

为了使用播放器,请初始化它并将IvsPlayerView添加到您的小部件树中:

import 'package:ivs_broadcaster/Player/ivs_player.dart';
import 'package:ivs_broadcaster/Player/ivs_player_view.dart';

IvsPlayer? ivsPlayer;

@override
void initState() {
  super.initState();
  ivsPlayer = IvsPlayer();
}

// 在您的小部件树中
child: IvsPlayerView(
  controller: ivsPlayer!,
  autoDispose: true,
  aspectRatio: 16 / 9,
),

这将提供相机预览。

示例代码

下面是一个完整的示例demo,展示了如何启动广播和播放功能:

import 'package:flutter/material.dart';
import 'home_page.dart'; // 假设这是您的广播页面
import 'player_page.dart'; // 假设这是您的播放页面

const String playBackUrl =
    "https://7453a0e95db4.us-east-1.playback.live-video.net/api/video/v1/us-east-1.655758237974.channel.TkU9oEEBXbzE.m3u8";

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: BroadCastWidget(),
    );
  }
}

class BroadCastWidget extends StatefulWidget {
  const BroadCastWidget({
    super.key,
  });

  @override
  State<BroadCastWidget> createState() => _BroadCastWidgetState();
}

class _BroadCastWidgetState extends State<BroadCastWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () async {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const HomePage(),
                  ),
                );
              },
              child: const Text('Start Broadcast'),
            ),
            ElevatedButton(
              onPressed: () async {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => PlayerPage(url: playBackUrl),
                  ),
                );
              },
              child: const Text('Start Player'),
            ),
          ],
        ),
      ),
    );
  }
}

请注意,您需要根据实际需求调整HomePagePlayerPage的实现细节。上述示例提供了基本框架,您可以在此基础上进一步扩展。


更多关于Flutter视频广播插件ivs_broadcaster的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter视频广播插件ivs_broadcaster的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 ivs_broadcaster 插件在 Flutter 中实现视频广播的示例代码。请注意,这个插件可能需要特定的配置和权限,并且由于版本更新,某些API可能会有所不同。确保你查阅了最新的官方文档以获取最新的信息。

首先,你需要在 pubspec.yaml 文件中添加 ivs_broadcaster 依赖:

dependencies:
  flutter:
    sdk: flutter
  ivs_broadcaster: ^最新版本号  # 请替换为实际的最新版本号

然后,运行 flutter pub get 来获取依赖。

接下来,在 android/app/src/main/AndroidManifest.xml 中添加必要的权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

此外,你还需要在 android/app/build.gradle 文件中配置最小SDK版本:

android {
    compileSdkVersion 31

    defaultConfig {
        applicationId "com.example.yourapp"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"
    }
    ...
}

接下来是 Flutter 代码部分,我们将展示如何初始化并使用 ivs_broadcaster 插件进行视频广播。

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:ivs_broadcaster/ivs_broadcaster.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('IVS Broadcaster Example'),
        ),
        body: Center(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late IvsBroadcaster _ivsBroadcaster;
  bool _isBroadcasting = false;

  @override
  void initState() {
    super.initState();
    _ivsBroadcaster = IvsBroadcaster();
    _checkPermissions();
  }

  Future<void> _checkPermissions() async {
    var status = await Permission.camera.status;
    if (!status.isGranted) {
      status = await Permission.camera.request();
      if (!status.isGranted) {
        // 权限被拒绝
        return;
      }
    }

    status = await Permission.microphone.status;
    if (!status.isGranted) {
      status = await Permission.microphone.request();
      if (!status.isGranted) {
        // 权限被拒绝
        return;
      }
    }

    // 初始化 IvsBroadcaster,配置等(具体配置根据需求调整)
    _initBroadcaster();
  }

  Future<void> _initBroadcaster() async {
    try {
      await _ivsBroadcaster.init(
        // 替换为你的配置信息
        rtmpUrl: 'rtmp://your_rtmp_server/live/stream_key',
        previewResolution: IvsBroadcasterPreviewResolution.resolution_720P,
        outputResolution: IvsBroadcasterOutputResolution.resolution_720P,
        fps: 30,
        bitrate: 2000000,
      );
      print('Broadcaster initialized');
    } catch (e) {
      print('Error initializing broadcaster: $e');
    }
  }

  Future<void> _startBroadcasting() async {
    if (_isBroadcasting) return;

    try {
      await _ivsBroadcaster.startBroadcasting();
      setState(() {
        _isBroadcasting = true;
      });
      print('Broadcasting started');
    } catch (e) {
      print('Error starting broadcasting: $e');
    }
  }

  Future<void> _stopBroadcasting() async {
    if (!_isBroadcasting) return;

    try {
      await _ivsBroadcaster.stopBroadcasting();
      setState(() {
        _isBroadcasting = false;
      });
      print('Broadcasting stopped');
    } catch (e) {
      print('Error stopping broadcasting: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: _isBroadcasting ? _stopBroadcasting : _startBroadcasting,
          child: Text(_isBroadcasting ? 'Stop Broadcasting' : 'Start Broadcasting'),
        ),
      ],
    );
  }
}

在这个示例中,我们检查了相机和麦克风的权限,初始化了 IvsBroadcaster,并提供了开始和停止广播的功能。注意,rtmpUrl 和其他配置参数需要根据你的实际RTMP服务器和流密钥进行替换。

此外,ivs_broadcaster 插件可能有一些特定的配置和生命周期管理要求,请务必查阅其官方文档以获取更详细的信息。

回到顶部