Flutter直播播放插件shoplive_player的使用
Flutter直播播放插件shoplive_player的使用
Shoplive SDK 示例用于 Flutter。
开始使用
直播播放器示例代码
以下是一个完整的示例代码,展示了如何使用 shoplive_player
插件来播放直播流。
import 'dart:convert';
import 'dart:developer' as Log;
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:rxdart/rxdart.dart';
import 'package:shoplive_player/shoplive_common.dart';
import 'package:shoplive_player/shoplive_player.dart';
import 'package:shoplive_player/shoplive_shortform.dart';
import 'package:shoplive_player/shoplive_streamer.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'ShopLive 测试',
routes: {
ShopLiveTestPage.routeName: (context) => const ShopLiveTestPage(),
},
initialRoute: ShopLiveTestPage.routeName,
);
}
}
class ShopLiveTestPage extends StatefulWidget {
static const routeName = '/';
const ShopLiveTestPage({Key? key}) : super(key: key);
[@override](/user/override)
State<ShopLiveTestPage> createState() => _ShopLiveTestPageState();
}
class _ShopLiveTestPageState extends State<ShopLiveTestPage> {
final CompositeSubscription _compositeSubscription = CompositeSubscription();
final String _accessKey = ""; // 替换为您的 Access Key
final String _campaignKey = ""; // 替换为您的 Campaign Key
final String _streamerToken = ""; // 替换为您的 Streamer Token
late final _shopLiveCommonPlugin = ShopLiveCommon();
late final _shopLivePlayerPlugin = ShopLivePlayer();
late final _shopLiveShortformPlugin = ShopLiveShortform();
late final _shopLiveStreamerPlugin = ShopLiveStreamer();
late final _accessKeyController =
TextEditingController(text: _accessKey); // 测试 AccessKey 的控制器
late final _campaignKeyController =
TextEditingController(text: _campaignKey); // 测试 CampaignKey 的控制器
late final _shareSchemeUrlController =
TextEditingController(text: "http://google.com"); // 分享方案 URL
late final _streamerTokenController =
TextEditingController(text: _streamerToken); // 测试 StreamerToken 的控制器
[@override](/user/override)
void initState() {
super.initState();
initListener();
}
void initListener() {
_shopLivePlayerPlugin.handleNavigation.listen((data) {
_showToast("handleNavigation : ${data.url}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.handleDownloadCoupon.listen((data) {
_showToast("handleDownloadCoupon : ${data.couponId}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.changeCampaignStatus.listen((data) {
_showToast("changeCampaignStatus : ${data.campaignStatus}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.campaignInfo.listen((data) {
_showToast(
"campaignInfo : ${const JsonEncoder().convert(data.campaignInfo)}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.handleCustomAction.listen((data) {
_showToast(
"handleCustomAction : ${data.id}, ${data.type}, ${data.payload}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.changedPlayerStatus.listen((data) {
_showToast("changedPlayerStatus: ${data.status}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.userInfo.listen((data) {
_showToast("userInfo : ${const JsonEncoder().convert(data.userInfo)}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.error.listen((data) {
_showToast("error : ${data.code}, ${data.message}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.receivedCommand.listen((data) {
_showToast(
"receivedCommand : ${data.command}, ${const JsonEncoder().convert(data.data)}");
}).addTo(_compositeSubscription);
_shopLivePlayerPlugin.log.listen((data) {
_showToast(
"clickLog : ${data.name}, ${data.feature}, ${data.campaignKey}, ${const JsonEncoder().convert(data.payload)}");
}).addTo(_compositeSubscription);
// 短视频事件监听器
_shopLiveShortformPlugin.onClickProduct.listen((data) {
_showToast("onClickProduct : ${data.productId} ");
}).addTo(_compositeSubscription);
_shopLiveShortformPlugin.onClickBanner.listen((data) {
_showToast("onClickBanner : ${data.url} ");
}).addTo(_compositeSubscription);
_shopLiveShortformPlugin.onShare.listen((data) {
_showToast("onClickShare : ${data.shortsId}, ${data.title} ");
}).addTo(_compositeSubscription);
_shopLiveShortformPlugin.onStart.listen((data) {
_showToast("onShortformStarted");
}).addTo(_compositeSubscription);
_shopLiveShortformPlugin.onClose.listen((data) {
_showToast("onShortformClosed");
}).addTo(_compositeSubscription);
_shopLiveShortformPlugin.log.listen((data) {
_showToast("onShortformEventLog : ${data.command}, ${data.payload} ");
}).addTo(_compositeSubscription);
// 短视频事件监听器结束
_shopLiveStreamerPlugin.error.listen((data) {
_showToast("onStreamerError : ${data.code}, ${data.message} ");
}).addTo(_compositeSubscription);
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Shoplive flutter 示例应用'),
),
body: Container(
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
margin: const EdgeInsets.all(20),
child: TextField(
controller: _accessKeyController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Access Key',
),
),
),
Container(
margin: const EdgeInsets.all(20),
child: TextField(
controller: _campaignKeyController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Campaign Key',
),
),
),
Container(
margin: const EdgeInsets.all(20),
child: TextField(
controller: _streamerTokenController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Streamer Token',
),
),
),
Container(
margin: const EdgeInsets.all(20),
child: TextField(
controller: _shareSchemeUrlController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: '分享方案 URL',
),
),
),
TextButton(
onPressed: () {
if (_accessKeyController.text.isEmpty) {
_showToast("请输入 Access Key");
return;
}
if (_campaignKeyController.text.isEmpty) {
_showToast("请输入 Campaign Key");
return;
}
_shopLivePlayerPlugin.setEnterPipModeOnBackPressed(
isEnterPipMode: true);
_shopLivePlayerPlugin.setMuteWhenPlayStart(isMute: false);
_shopLivePlayerPlugin.setMixWithOthers(isMixAudio: true);
_shopLivePlayerPlugin.useCloseButton(canUse: true);
_shopLivePlayerPlugin.setShareScheme(
shareSchemeUrl: _shareSchemeUrlController.text.isNotEmpty
? _shareSchemeUrlController.text
: "http://google.com");
_shopLiveCommonPlugin.setUser(
accessKey: _accessKeyController.text,
user: ShopLiveCommonUser(
userId: "userId",
userName: "测试用户",
userScore: 0,
gender: ShopLiveCommonUserGender.NEUTRAL,
age: 20,
custom: {"key": "value"},
));
_shopLiveCommonPlugin.setAccessKey(
accessKey: _accessKeyController.text);
_shopLivePlayerPlugin.play(
data: ShopLivePlayerData(
campaignKey: _campaignKeyController.text));
},
child: const Text('播放直播'),
),
TextButton(
onPressed: () {
if (_accessKeyController.text.isEmpty) {
_showToast("请输入 Access Key");
return;
}
if (_campaignKeyController.text.isEmpty) {
_showToast("请输入 Campaign Key");
return;
}
_shopLivePlayerPlugin.setEnterPipModeOnBackPressed(
isEnterPipMode: true);
_shopLivePlayerPlugin.setMuteWhenPlayStart(isMute: false);
_shopLivePlayerPlugin.setMixWithOthers(isMixAudio: true);
_shopLivePlayerPlugin.useCloseButton(canUse: true);
_shopLivePlayerPlugin.setShareScheme(
shareSchemeUrl: _shareSchemeUrlController.text.isNotEmpty
? _shareSchemeUrlController.text
: "http://google.com");
_shopLiveCommonPlugin.setUser(
accessKey: _accessKeyController.text,
user: ShopLiveCommonUser(
userId: "userId",
userName: "测试用户",
userScore: 0,
gender: ShopLiveCommonUserGender.NEUTRAL,
age: 20,
custom: {"key": "value"},
));
_shopLiveCommonPlugin.setAccessKey(
accessKey: _accessKeyController.text);
_shopLivePlayerPlugin.showPreview(
data: ShopLivePlayerPreviewData(
campaignKey: _campaignKeyController.text,
useCloseButton: true,
));
},
child: const Text('预览直播'),
),
TextButton(
onPressed: () {
if (_accessKeyController.text.isEmpty) {
_showToast("请输入 Access Key");
return;
}
_shopLiveCommonPlugin.setUser(
accessKey: _accessKeyController.text,
user: ShopLiveCommonUser(
userId: "userId",
userName: "测试用户",
userScore: 0,
gender: ShopLiveCommonUserGender.NEUTRAL,
age: 20,
custom: {"key": "value"},
));
_shopLiveCommonPlugin.setAccessKey(
accessKey: _accessKeyController.text,
);
_shopLiveShortformPlugin.play(
data: ShopLiveShortformCollectionData());
},
child: const Text('播放短视频'),
),
TextButton(
onPressed: () {
if (_accessKeyController.text.isEmpty) {
_showToast("请输入 Access Key");
return;
}
if (_streamerTokenController.text.isEmpty) {
_showToast("请输入 Streamer Token");
return;
}
if (!Platform.isAndroid) {
_showToast("仅支持 Android 平台");
return;
}
_shopLiveCommonPlugin.setAccessKey(
accessKey: _accessKeyController.text,
);
_shopLiveCommonPlugin.setStreamerToken(
streamerJWT: _streamerTokenController.text,
);
_shopLiveStreamerPlugin.play();
},
child: const Text('播放主播流 - 仅限 Android'),
),
],
),
),
),
);
}
[@override](/user/override)
void dispose() {
_accessKeyController.dispose();
_campaignKeyController.dispose();
_streamerTokenController.dispose();
_shareSchemeUrlController.dispose();
_compositeSubscription.dispose();
super.dispose();
}
void _showToast(String text) {
Log.log(text);
Fluttertoast.showToast(
msg: text,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black.withOpacity(0.7),
textColor: Colors.white,
fontSize: 14.0,
);
}
}
更多关于Flutter直播播放插件shoplive_player的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter直播播放插件shoplive_player的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
shoplive_player
是一个用于在 Flutter 应用中播放直播流的插件。它通常用于集成直播功能,支持多种直播协议和格式。以下是如何在 Flutter 项目中使用 shoplive_player
的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 shoplive_player
插件的依赖。
dependencies:
flutter:
sdk: flutter
shoplive_player: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来获取依赖。
2. 导入插件
在你的 Dart 文件中导入 shoplive_player
插件。
import 'package:shoplive_player/shoplive_player.dart';
3. 使用 ShoplivePlayer
你可以在你的 Flutter 应用中使用 ShoplivePlayer
组件来播放直播流。
class LiveStreamPage extends StatelessWidget {
final String streamUrl = "https://your-live-stream-url.com/stream.m3u8";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Live Stream'),
),
body: Center(
child: ShoplivePlayer(
streamUrl: streamUrl,
autoPlay: true,
looping: false,
onError: (error) {
print("Error occurred: $error");
},
onPlay: () {
print("Playback started");
},
onPause: () {
print("Playback paused");
},
onComplete: () {
print("Playback completed");
},
),
),
);
}
}
4. 配置参数
ShoplivePlayer
组件支持多个参数来配置播放器的行为:
streamUrl
: 直播流的 URL。autoPlay
: 是否自动开始播放。looping
: 是否循环播放。onError
: 播放出错时的回调。onPlay
: 播放开始时的回调。onPause
: 播放暂停时的回调。onComplete
: 播放完成时的回调。
5. 处理播放器事件
你可以通过回调函数来处理播放器的各种事件,例如播放、暂停、错误等。
6. 运行应用
确保你的设备或模拟器已经连接,然后运行你的 Flutter 应用。
flutter run
7. 其他注意事项
- 确保你的直播流 URL 是有效的,并且支持
shoplive_player
插件所支持的协议(如 HLS、RTMP 等)。 - 如果你遇到播放问题,请检查网络连接和直播流的可用性。
8. 自定义 UI
你可以根据需要自定义播放器的 UI,例如添加播放/暂停按钮、进度条等。
ShoplivePlayer(
streamUrl: streamUrl,
autoPlay: true,
looping: false,
onError: (error) {
print("Error occurred: $error");
},
onPlay: () {
print("Playback started");
},
onPause: () {
print("Playback paused");
},
onComplete: () {
print("Playback completed");
},
child: Column(
children: [
// 自定义 UI 组件
IconButton(
icon: Icon(Icons.play_arrow),
onPressed: () {
// 控制播放器
},
),
],
),
)