Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter video caching for 10 seconds on next 4 videos

Does anyone know how to do Flutter Video Caching in List for 4 to 6 seconds? (For next 5 videos) like Instagram reels.

Is there any way to do it?

I had taken PageView.builder to show a video with a full page.

I have tried one cached_video_player but it's loading full video.

Here is what I have done.

VideoWidget:

typedef OnVideoCompleted = void Function();

class VideoWidget extends StatefulWidget {
  //final bool? play;
  final bool? isDuetVideo;
  final String? url;
  final OnVideoCompleted? onVideoCompleted;
  final HomeWidgetBloc? homeWidgetBloc;

  const VideoWidget(
      {Key? key,
      this.onVideoCompleted,
      required this.url,
      required this.homeWidgetBloc,
      required this.isDuetVideo})
      : super(key: key);

  @override
  _VideoWidgetState createState() => _VideoWidgetState();
}

class _VideoWidgetState extends State<VideoWidget> {
  late VideoPlayerController videoPlayerController;
  late Future<void> _initializeVideoPlayerFuture;
  final _controllerStateStream = BehaviorSubject<int>.seeded(0);
  VoidCallback? _listener;
  StreamSubscription? _playPauseSubscription;

  @override
  void initState() {
    super.initState();
    videoPlayerController = new VideoPlayerController.network(widget.url!);
    videoPlayerController.initialize().then((_) {
      //       Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
      _controllerStateStream.add(1);
      _observeForPlayPause();
      _observerForSeekDuration();
      _listener = () {
        final value =
            widget.homeWidgetBloc?.videoEndedStream.valueWrapper?.value;
        print('duration -----value--- ${value}');
        if (videoPlayerController.value.duration.inSeconds > 0 &&
            videoPlayerController.value.position.inMilliseconds ==
                videoPlayerController.value.duration.inMilliseconds &&
            (videoPlayerController.value.position.inMilliseconds ==
                videoPlayerController.value.duration.inMilliseconds)) {
          // FOR AUTO PLAY NEXT VIDEO...
          widget.onVideoCompleted?.call();
          print(
              'duration -----addListener--- ${videoPlayerController.value.duration}');
        }
      };
      videoPlayerController.addListener(_listener!);
    });
  } // This closing tag was missing

  @override
  void dispose() {
    super.dispose();
    _controllerStateStream.close();
    _playPauseSubscription?.cancel();
    try {
      if (_listener != null) {
        videoPlayerController.removeListener(_listener!);
      }
      videoPlayerController.dispose();
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<int>(
      stream: _controllerStateStream,
      builder: (context, snapshot) {
        final isReady = (snapshot.data ?? 0) == 1;

        if (!isReady) {
          return _progressWidget();
        }

        return new Stack(children: <Widget>[
          Container(
            child: Center(
              child: (widget.isDuetVideo! ||
                      videoPlayerController.value.size.width >
                          videoPlayerController.value.size.height)
                  ? AspectRatio(
                      child: VideoPlayer(
                        videoPlayerController,
                      ),
                      aspectRatio: videoPlayerController.value.aspectRatio,
                    )
                  : VideoPlayer(
                      videoPlayerController,
                    ),
              widthFactor: double.maxFinite,
              heightFactor: double.maxFinite,
            ),
          ),
          Visibility(
            visible: !widget.isDuetVideo!,
            child: VideoPlayerCustomControlsWidget(
              controller: videoPlayerController,
            ),
          ),
        ]);
      },
    );
  }

  Center _progressWidget() {
    return Center(
      child: CircularProgressIndicator(
        color: AppStyles.primary500Color,
      ),
    );
  }

  void _observeForPlayPause() {
    _playPauseSubscription =
        widget.homeWidgetBloc?.videoPlayPauseStream.listen((value) {
      if (value == PLAY)
        videoPlayerController.play();
      else
        videoPlayerController.pause();
    });
  }

  void _observerForSeekDuration() {
    _playPauseSubscription =
        widget.homeWidgetBloc?.duetVideoSeekDurationZeroStream.listen((value) {
      if (value == true) videoPlayerController.seekTo(Duration.zero);
      widget.homeWidgetBloc?.duetVideoSeekDurationZeroStream.add(false);
    });
  }
}

Update:

I found many answers (like this) but that all answers are only for caching the current video, not the next/prev videos from the list. I want it, especially for the list.

like image 527
Pratik Butani Avatar asked Sep 13 '21 18:09

Pratik Butani


People also ask

How do you cache videos on flutter?

Another Solution: Is to stream the video normally using the official plugin and to cache the video file using flutter_cache_manager simultaneously. Here how the scenario would goes: 1- Check with flutter_cache_manager if the video_url is already downloaded and cached.

How do you autoplay videos on flutter?

Based on this post's answer, you can use the WidgetsBinding. instance. addPostFrameCallback to autoplay your video.

How to play videos in flutter?

In Flutter, videos are handled through the use of video_player plugin. This performs tasks like playing a video, pausing a video, or muting the same. It can be used to play videos from the internet or the videos stored in the assets of the application. In this article, we will explore the same in detail through an example application.

How do I increase the cache size of flutter video player?

To adjust the cache size: VideoPlayerController.setCacheSize (100 * 1024 * 1024, 200 * 1024 * 1024); Another Solution: Is to stream the video normally using the official plugin and to cache the video file using flutter_cache_manager simultaneously.

What is flutter_cache_manager and how to use it?

After a quick google search I came across flutter_cache_manager – a cache manager that downloads and cache files in the the cache directory of the app. All I needed to do was to put everything together in a nice and maintenable way which is what I’m going to talk about in the example below.

Is there a way to cache first 10 seconds programmatically?

Even if you cant find a way to cache first 10 seconds programmatically, you can still add a microservice that runs from same server and visits first 10 seconds of videos that should keep the data in cache until client arrives next video. This is not efficient tho.


Video Answer


1 Answers

this is what I used in my app, preload_page_view, it preloads a specific count of pre/next pages:

  @override
  Widget build(BuildContext context) {
    return new PreloadPageView.builder(
      itemCount: ...,
      itemBuilder: ...,
      onPageChanged: (int position) {...},
      .....
      preloadPagesCount: 3,
      controller: PreloadPageController(),
    );
  }
like image 120
Jim Avatar answered Oct 22 '22 00:10

Jim