yogender
yogender

Reputation: 252

Video not playing in flutter web application

I am trying to use Viedo as a backgrounnd for scaffold widget in flutter web application but the video is not displayed though it's working fine in android but is not displayed in web neither it's giving any sort of error.

I am using this plugin to implement video player https://pub.dev/packages/video_player

My code :

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  VideoPlayerController? _videoPlayerController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _videoPlayerController =
    VideoPlayerController.asset("assets/backgroundVideo.mp4")
      ..initialize().then((_) {
        _videoPlayerController!.play();
        _videoPlayerController!.setLooping(true);
        setState(() {});
      });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
          body: Stack(
            children: <Widget>[
              SizedBox.expand(
                child: FittedBox(
                  fit: BoxFit.fill,
                  child: SizedBox(
                    width: _videoPlayerController!.value.size.width ?? 0,
                    height: _videoPlayerController!.value.size.height ?? 0,
                    child: VideoPlayer(_videoPlayerController!),
                  ),
                ),
              ),
              Container(
                width: 100,
                height: 100,
                child: Text("Hi"),
              )
            ],
          ),
        ));
  }
}

Upvotes: 3

Views: 7676

Answers (4)

aolsan
aolsan

Reputation: 494

According to the updated Chrome Policy as at Dec 15,2022, If you want to autoplay videos without user interaction on web.You should Have the audio muted on initialization. so say you initialised in initState().

  late VideoPlayerController _videoPlayerController;

  @override
  void initState() {
    super.initState();
    _videoPlayerController =
        VideoPlayerController.asset("assets/videoplayback.mp4")
          ..initialize().then((_) {
            _videoPlayerController.setVolume(0);
            _videoPlayerController.play();
            _videoPlayerController.setLooping(true);
            setState(() {});
          });
  }

Upvotes: 9

mhr
mhr

Reputation: 154

It's most probably because the video wants to auto play without the user having any interaction with the browser tab. Read it here which says:

Playing videos without prior interaction with the site might be prohibited by the browser and lead to runtime errors.

If you want to avoid it, provide the play button to the user so that they can play the video themselves or if you really want it auto-played, an idea could be to add a button somewhere before the video wants to auto-play. A button which would only be there to have the user's first interaction with the tab!

Upvotes: 1

Try it using futurebuilder.

       import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:provider/provider.dart';


class VolumeManager with ChangeNotifier{
  var _volume=50.0;
  double get volume=>_volume;

  void setVolume({
    required double volumeValue,
    required VideoPlayerController controller
  }){
    _volume=volumeValue;
    controller.setVolume(_volume);
    notifyListeners();
  }
}

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test Video',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:
       ChangeNotifierProvider(create:(context)=>VolumeManager(),child: Test_LoadVideoWidget()),
    );
  }
}

class Test_LoadVideoWidget extends StatefulWidget {
  Test_LoadVideoWidget({Key? key}) : super(key: key);

  @override
  State<Test_LoadVideoWidget> createState() => _Test_LoadVideoWidgetState();
}

class _Test_LoadVideoWidgetState extends State<Test_LoadVideoWidget> {
  late final VideoPlayerController controller;
  late final Future<void>initVideo;

    @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller=VideoPlayerController.asset("assets/video/butterfly.mp4");
    //..initialize().then((_){
      //controller.play();
      //controller.setLooping(true);
     setState(() {
       });
 
    //});
       initVideo = controller.initialize();
     
     
  }
  @override
  void dispose() {
    // TODO: implement dispose
    controller.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    //return Test_VideoWidget(controller);


      return FutureBuilder<void>(
      future:initVideo,
      builder:(context,snapshot){
        if (snapshot.connectionState==ConnectionState.done){
          return Test_VideoWidget(controller);
        }
        return Center(child:CircularProgressIndicator());
      }
    );
       
  }
}

class Test_VideoWidget extends StatelessWidget {
  final VideoPlayerController controller;
  Test_VideoWidget(this.controller);

  void _play(){
     if (!controller.value.isPlaying){
       controller.play();
     }
  }
  void _pause(){
     if (controller.value.isPlaying){
       controller.pause();
     }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title:Text("Test Video",style:Theme.of(context).textTheme.headline2)),
    body:
//        controller.value.isInitialized?
    Container(
      width:MediaQuery.of(context).size.width,
      height:MediaQuery.of(context).size.height,
      padding:EdgeInsets.all(20),child:
    SingleChildScrollView(child:Column(
      mainAxisAlignment:MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        AspectRatio(aspectRatio: controller.value.aspectRatio,
        child:VideoPlayer(controller),
        ),
        SingleChildScrollView(scrollDirection: Axis.horizontal, child: Row(children: [
          SizedBox(width:200,child:ElevatedButton(onPressed: (){_play();}, child: Text("Play!",style:Theme.of(context).textTheme.button))),
          const SizedBox(height:50,width:200),
          SizedBox(width:200,child:ElevatedButton(onPressed:(){_pause();}, child:Text("Pause",style:Theme.of(context).textTheme.button))),
      ],))
      ,Consumer<VolumeManager>(
        builder:(context,manager,_)=>
        Slider(
              min: 0,
              max: 50,
              value: manager.volume,
              onChanged: (value) =>
              {
                  manager.setVolume(volumeValue: value, controller: controller)
              }
          ),
      )
    ],)
    )
    //:
      //  Center(child:CircularProgressIndicator()),
    ));
  }
}

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63594

1st add video_player_web: ^2.0.2 on pubspec.yaml.

Then run this widget. Don't just hot-restart, run/rebuild again.

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class HomeLocalVideo extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<HomeLocalVideo> {
  late VideoPlayerController _videoPlayerController;

  @override
  void initState() {
    super.initState();
    _videoPlayerController =
        VideoPlayerController.asset("assets/videoplayback.mp4")
          ..initialize().then((_) {
            _videoPlayerController.play();
            _videoPlayerController.setLooping(true);
            setState(() {});
          });
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: _videoPlayerController.value.isInitialized
            ? Stack(
                children: <Widget>[
                  SizedBox.expand(
                    child: FittedBox(
                      fit: BoxFit.fill,
                      child: SizedBox(
                        width: _videoPlayerController.value.size.width,
                        height: _videoPlayerController.value.size.height,
                        child: VideoPlayer(_videoPlayerController),
                      ),
                    ),
                  ),
                  Container(
                    width: 100,
                    height: 100,
                    child: Text("Hi"),
                  )
                ],
              )
            : Container(),
      ),
    );
  }
}

Upvotes: 2

Related Questions