Dave
Dave

Reputation: 5416

Flutter better_player: How to play video from local assets folder

Q) Anyone know how to reference a file locally for both iOS and Android with better_player?

I cannot find a way to do this with their docs, I know it can be done with the in-house Flutter VideoPlayer plugin BUT I want to use better_player instead.

This works with the standard video plugin:

_videoController = VideoPlayerController.asset('assets/intro.mp4');

e.g. load a video in the project root at /assets/intro.mp4

I've tried this with better_player, but it doesn't find the file:

    BetterPlayerDataSource betterPlayerDataSource = BetterPlayerDataSource(
        BetterPlayerDataSourceType.file, "assets/sample.mp4");

Upvotes: 3

Views: 5455

Answers (2)

Dave
Dave

Reputation: 5416

So first I had to copy the file to the ApplicationDocuments directory

  void _copyAssetToLocal() async {
    try {
      var content = await rootBundle.load("assets/intro.mp4");
      final directory = await getApplicationDocumentsDirectory();
      var file = File("${directory.path}/intro.mp4");
      file.writeAsBytesSync(content.buffer.asUint8List());
      _loadIntroVideo(file.path);
    } catch (e) {
      print("crap");
    }
  }

Then I could load it up from the new fullPath just created.

  void _loadIntroVideo(String fullPath) {
    var config = BetterPlayerConfiguration(
      fit: BoxFit.cover,
      autoPlay: true,
      fullScreenByDefault: false,
      // ...
    );

    BetterPlayerDataSource betterPlayerDataSource =
          BetterPlayerDataSource(BetterPlayerDataSourceType.file, fullPath);

    // etc
  }

Upvotes: 3

Kyrill
Kyrill

Reputation: 334

my example:

videoPage.dart

import 'package:better_player/better_player.dart';
import 'package:better_player_example/utils.dart';
import 'package:flutter/material.dart';

return Scaffold(
          appBar: AppBar(
            title: Text("better player example"),
          ),
          body: Column(
            children: [
              FutureBuilder<String>(
                future: Utils.getFileUrl("testvideo.mp4"),
                builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                  if (snapshot.data != null) {
                    return BetterPlayer.file(snapshot.data!);
                  } else {
                    return const SizedBox();
                  }
                },
              )
            ],
          ),
        );

utils.dart

import 'package:path_provider/path_provider.dart';

class Utils {
  static Future<String> getFileUrl(String fileName) async {
    final directory = await getApplicationDocumentsDirectory();
    return "${directory.path}/$fileName";
  }
}

Upvotes: 0

Related Questions