byteplus_vod 1.44.2-1 copy "byteplus_vod: ^1.44.2-1" to clipboard
byteplus_vod: ^1.44.2-1 copied to clipboard

This Flutter plugin provides vod player sdk native APIs for you to implement video play functions in your application

example/lib/main.dart

// ignore_for_file: prefer_const_constructors, unused_import

import 'dart:io';
import 'dart:ui';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:byteplus_vod/ve_vod.dart';
import 'package:vod_player_flutter_example/global_configuration.dart';
import 'package:vod_player_flutter_example/home/play_setting_page.dart';
import 'package:vod_player_flutter_example/platform_keys.dart';
import 'package:vod_player_flutter_example/short_video_play_scene.dart';
import 'package:vod_player_flutter_example/short_video/short_video_feed_item.dart';
import 'package:vod_player_flutter_example/short_video/short_video_feed_util.dart';
import 'package:vod_player_flutter_example/video_preload.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  List<ShortVideoFeedItem>? shortVideofeedlist;
  final String _appID = '229234';

  @override
  void initState() {
    super.initState();

    initPlatformState();

    Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> result) {
      if (result.contains(ConnectivityResult.none)) {
        Fluttertoast.showToast(msg: "网络连接失败,请稍后重试", gravity: ToastGravity.BOTTOM);
      } else {
        fetchShortVideoFeed();
      }
      // Received changes in available connectivity types!
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // open log module
    await FlutterTTSDKManager.openAllLog();

    // regist log callback
    TTFLogger.onLog = (logLevel, msg) {
      print(msg);
    };

    String licPath = 'assets/VEVod.license';
    // please replace it with current channel, example "App Store" for iOS
    String channel = Platform.isAndroid ? 'demo_channel_android' : 'App Store';
    TTSDKVodConfiguration vodConfig = TTSDKVodConfiguration();
    vodConfig.cacheMaxSize = 300 * 1024 * 1024;
    TTSDKConfiguration sdkConfig = TTSDKConfiguration.defaultConfigurationWithAppIDAndLicPath(
        appID: _appID, licenseFilePath: licPath, channel: channel);
    sdkConfig.vodConfiguration = vodConfig;
    sdkConfig.appName = "bytevod_flutter_demo";
    sdkConfig.appVersion = "1.1.1";
    FlutterTTSDKManager.startWithConfiguration(sdkConfig);
    // deviceID
    FlutterTTSDKManager.setCurrentUserUniqueID('test_1234');
    String? uniqueID = await FlutterTTSDKManager.getCurrentUserUniqueID();
    String? deviceID = await FlutterTTSDKManager.getDeviceID();
    String? engineUniqueId = await FlutterTTSDKManager.getEngineUniqueId();
    print("TTF -- uniqueId:$uniqueID deviceId:$deviceID engineUniqueId:$engineUniqueId");

    // strategy
    updateStrategy();

    if (!mounted) return;
    setState(() {});
  }

  Future<void> updateStrategy() async {
    await GlobalConfiguration.initSharedPreferences();
    if (GlobalConfiguration.enableStrategyPreload && GlobalConfiguration.enableStrategyPreRender) {
      TTVideoEngineStrategy.enableEngineStrategy(
          strategyType: TTVideoEngineStrategyType.preloadAndPreRender, scene: TTVideoEngineStrategyScene.smallVideo);
      _enableEnginePreRenderStrategy(true);
    } else if (GlobalConfiguration.enableStrategyPreload) {
      TTVideoEngineStrategy.enableEngineStrategy(
          strategyType: TTVideoEngineStrategyType.preload, scene: TTVideoEngineStrategyScene.smallVideo);
    } else if (GlobalConfiguration.enableStrategyPreRender) {
      TTVideoEngineStrategy.enableEngineStrategy(
          strategyType: TTVideoEngineStrategyType.preRender, scene: TTVideoEngineStrategyScene.smallVideo);
      _enableEnginePreRenderStrategy(true);
    } else {
      TTVideoEngineStrategy.clearAllEngineStrategy();
    }
  }

  Future<void> fetchShortVideoFeed() async {
    ShortVideoFeedUtil.requestFeed((List<ShortVideoFeedItem>? feedlist) {
      if (feedlist != null) {
        setState(() {
          shortVideofeedlist = feedlist;
          syncStrategyList();
        });
      } else {
        Fluttertoast.showToast(msg: "获取数据异常,请退出重试", gravity: ToastGravity.CENTER);
      }
    });
  }

  Future<void> syncStrategyList() async {
    List<TTVideoEngineMediaSource> ss = [];
    for (int i = 0; i < shortVideofeedlist!.length; i++) {
      ShortVideoFeedItem item = shortVideofeedlist![i];
      TTVideoEngineVidSource source = TTVideoEngineVidSource.init(
          vid: item.vid,
          playAuthToken: item.playAuthToken,
          resolution: TTVideoEngineResolutionType.TTVideoEngineResolutionTypeHD);
      ss.add(source);
    }
    TTVideoEngineStrategy.setStrategyVideoSources(videoSources: ss);
  }

  Future<void> _enableEnginePreRenderStrategy(bool enable) async {
    if (enable) {
      TTVideoEngineStrategy.init();
      TTVideoEngineStrategy.onCreatePreRenderEngine = ((source) async {
        VodPlayerFlutter player = VodPlayerFlutter();
        String coreHashHex = await player.createPlayer(vid: source.getVid, preCreated: true);
        player.setMediaSource(source);
        player.setHardwareDecode(GlobalConfiguration.isHardwareDecode);
        player.setTrackVolumeEnabled(GlobalConfiguration.isTrackVolume);
        player.setScalingMode(TTVideoEngineScalingMode.TTVideoEngineScalingModeAspectFit);
        player.openTextureRender(!GlobalConfiguration.closeTextureRender);
        player.setLooping(true);
        player.setCustomHeader('x-tt-flutter-test-demo', '1');
        print(
            'TTF -- TTVideoEngineStrategyPreRender onCreatePreRenderEngine, hashCode:${player.hashCode} engine:$coreHashHex vid:${source.getVid}');
        return player;
      });
      print('TTF -- TTVideoEngineStrategyPreRender - init end');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Builder(
      builder: (context) => Scaffold(
        backgroundColor: const Color.fromRGBO(244, 245, 247, 1),
        body: Padding(
          padding: EdgeInsets.zero,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                  height: 280,
                  color: Colors.transparent,
                  child: Stack(
                    children: [
                      Image.asset(
                        'assets/images/icon_home_background.png',
                      ),
                      const Positioned(
                        top: 180,
                        left: 30,
                        child: Text('视频点播',
                            style: TextStyle(color: Colors.black, fontSize: 24, fontWeight: FontWeight.bold)),
                      ),
                      const Positioned(
                        top: 220,
                        left: 30,
                        child: Text('体验一站式视频解决方案', style: TextStyle(color: Colors.black, fontSize: 16)),
                      ),
                    ],
                  ),
                ),
                Container(
                  height: 75,
                  color: Colors.white,
                  margin: const EdgeInsets.symmetric(horizontal: 10),
                  alignment: Alignment.centerLeft,
                  child: Row(
                    // mainAxisAlignment: MainAxisAlignment.center, // 垂直居中
                    // crossAxisAlignment: CrossAxisAlignment.start, // 水平居左
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 30),
                        child: Image.asset('assets/images/icon_short.png', width: 28, height: 28),
                      ),
                      SizedBox(width: 10), // 第一个和第二个子组件之间的间距
                      TextButton(
                        onPressed: () {
                          if (shortVideofeedlist == null) {
                            Fluttertoast.showToast(msg: "暂无数据 请稍后重试");
                          } else {
                            if (_appID.isEmpty) {
                              Fluttertoast.showToast(
                                  msg: "Please contact Volcano Engine Business to get the demo AppId and License.",
                                  gravity: ToastGravity.CENTER);
                              return;
                            }
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ShortVideoScene(
                                  feedlist: shortVideofeedlist!,
                                ),
                              ),
                            );
                          }
                        },
                        style: ButtonStyle(
                          overlayColor: MaterialStateProperty.resolveWith<Color>(
                            (Set<MaterialState> states) {
                              // 当按钮被按下时返回透明色
                              return Colors.transparent;
                            },
                          ),
                        ),
                        child: Text('短视频(竖屏类抖音)',
                            style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w200)),
                      ),
                      Spacer(),
                      Image.asset('assets/images/main_arrow_right.png', width: 16, height: 16),
                      SizedBox(width: 20)
                    ],
                  ),
                ),
                SizedBox(height: 10),
                Container(
                  height: 75,
                  color: Colors.white,
                  margin: const EdgeInsets.symmetric(horizontal: 10),
                  alignment: Alignment.centerLeft,
                  child: Row(
                    // mainAxisAlignment: MainAxisAlignment.center, // 垂直居中
                    // crossAxisAlignment: CrossAxisAlignment.start, // 水平居左
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 30),
                        child: Image.asset('assets/images/icon_setting.png', width: 28, height: 28),
                      ),
                      SizedBox(width: 10), // 第一个和第二个子组件之间的间距
                      TextButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const PlaySettingPage(),
                            ),
                          );
                        },
                        style: ButtonStyle(
                          overlayColor: MaterialStateProperty.resolveWith<Color>(
                            (Set<MaterialState> states) {
                              // 当按钮被按下时返回透明色
                              return Colors.transparent;
                            },
                          ),
                        ),
                        child: Text('播放设置',
                            style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w200)),
                      ),
                      Spacer(),
                      Image.asset('assets/images/main_arrow_right.png', width: 16, height: 16),
                      SizedBox(width: 20)
                    ],
                  ),
                ),
                Spacer(),
                Container(
                  height: 75,
                  margin: const EdgeInsets.symmetric(horizontal: 10),
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center, // 垂直居中
                    crossAxisAlignment: CrossAxisAlignment.center, // 水平居左
                    children: const [
                      Text('ve_vod version: ${FlutterTTSDKManager.TTSDK_FLUTTER_VERSION}',
                          style: TextStyle(
                              color: Color.fromRGBO(170, 170, 170, 1), fontSize: 14, fontWeight: FontWeight.w300)),
                      Text('Beijing Volcano Engine Technology Co.,Ltd.',
                          style: TextStyle(
                              color: Color.fromRGBO(170, 170, 170, 1), fontSize: 14, fontWeight: FontWeight.w300)),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    ));
  }
}
0
likes
140
points
243
downloads

Publisher

unverified uploader

Weekly Downloads

This Flutter plugin provides vod player sdk native APIs for you to implement video play functions in your application

Homepage

Documentation

API reference

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on byteplus_vod