I am working on modifying the image_picker plugin for flutter. I have everything working accept when I return the data back to the flutter app I need help to figure out how to display the video back the user similar to how I would using Image.file for a picture. Then they can click to upload and when I retrieve need to play it, looked at the video_player plugin, but really only care to have them use the default platform player, but if I can get it to work then the plugin is fine, but no luck so far even seeing the video. The data returned from the image_picker plugin is a File, I determine that its not a image and go from there.
Any assistance would be great and I can show any code if it helps.
Thanks
Good thing that the image_picker is picking videos now.
If you'll run the sample app this is how it looks:
And here is another example where you can play and pause the video that you've uploaded from your local files using the image_picker and playing it using video_player as recommended in the Flutter documentation.
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
void main() => runApp(VideoPlayerApp());
class VideoPlayerApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Video Player Demo',
home: VideoPlayerScreen(),
);
}
}
class VideoPlayerScreen extends StatefulWidget {
VideoPlayerScreen({Key key}) : super(key: key);
#override
_VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
VideoPlayerController _controller;
Future<void> _initializeVideoPlayerFuture;
File videoFile;
#override
void initState() {
// Create and store the VideoPlayerController. The VideoPlayerController
// offers several different constructors to play videos from assets, files,
super.initState();
}
#override
void dispose() {
// Ensure disposing of the VideoPlayerController to free up resources.
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sample Video Player Demo'),
),
// Use a FutureBuilder to display a loading spinner while waiting for the
// VideoPlayerController to finish initializing.
body: Column(
children: <Widget>[
Visibility(
visible: _controller != null,
child: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the VideoPlayerController has finished initialization, use
// the data it provides to limit the aspect ratio of the video.
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
// Use the VideoPlayer widget to display the video.
child: VideoPlayer(_controller),
);
} else {
// If the VideoPlayerController is still initializing, show a
// loading spinner.
return Center(child: CircularProgressIndicator());
}
},
),
),
Center(
child: MaterialButton(
hoverColor: Colors.blue,
child: Text("Upload Video"),
onPressed: () {
getVideo();
},
),
),
],
),
floatingActionButton: _controller == null
? null
: FloatingActionButton(
onPressed: () {
// Wrap the play or pause in a call to `setState`. This ensures the
// correct icon is shown.
setState(() {
// If the video is playing, pause it.
if (_controller.value.isPlaying) {
_controller.pause();
} else {
// If the video is paused, play it.
_controller.play();
}
});
},
// Display the correct icon depending on the state of the player.
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Future getVideo() async {
var picker;
Future<File> _videoFile =
ImagePicker.pickVideo(source: ImageSource.gallery);
_videoFile.then((file) async {
setState(() {
videoFile = file;
_controller = VideoPlayerController.file(videoFile);
// Initialize the controller and store the Future for later use.
_initializeVideoPlayerFuture = _controller.initialize();
// Use the controller to loop the video.
_controller.setLooping(true);
});
});
}
}
Actual output:
Related
I am using the Flutter Video_Player plugin and am noticing some issues when I want to fast forward 10 seconds, so want to check if I am using the correct code.
What I am experiencing is that is takes a long time, to fast forward the play, if this happens then the tendency is to press fast forward again, and If I press it several times then i notice that the sound either is not in sync or can't be heard any longer.
Here is my code:
GestureDetector(
onTap: () async {
print('FORWARD 10 SECS');
await _controller.seekTo(Duration(
seconds:
_controller.value.position.inSeconds + 10));
},
I'd really appreciate it if I can get some help with this as the app I am working on is video focused so these controls do have to work correctly.
Thank you so much for any help with this. If you have any questions please let me know.
You don't need to await seekTo(), here is working code:
Check the complete code, hope it can help :)
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() => runApp(const VideoPlayerApp());
class VideoPlayerApp extends StatelessWidget {
const VideoPlayerApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Video Player Demo',
home: VideoPlayerScreen(),
);
}
}
class VideoPlayerScreen extends StatefulWidget {
const VideoPlayerScreen({Key? key}) : super(key: key);
#override
_VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
late VideoPlayerController _controller;
late Future<void> _initializeVideoPlayerFuture;
#override
void initState() {
// Create and store the VideoPlayerController. The VideoPlayerController
// offers several different constructors to play videos from assets, files,
// or the internet.
_controller = VideoPlayerController.network(
'https://media.w3.org/2010/05/sintel/trailer.mp4',
);
// Initialize the controller and store the Future for later use.
_initializeVideoPlayerFuture = _controller.initialize();
// Use the controller to loop the video.
_controller.setLooping(true);
super.initState();
_controller.play();
}
#override
void dispose() {
// Ensure disposing of the VideoPlayerController to free up resources.
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Video'),
),
// Use a FutureBuilder to display a loading spinner while waiting for the
// VideoPlayerController to finish initializing.
body: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the VideoPlayerController has finished initialization, use
// the data it provides to limit the aspect ratio of the video.
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
// Use the VideoPlayer widget to display the video.
child: VideoPlayer(_controller),
);
} else {
// If the VideoPlayerController is still initializing, show a
// loading spinner.
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Duration currentPosition = _controller.value.position;
Duration targetPosition = currentPosition + const Duration(seconds: 10);
_controller.seekTo(targetPosition);
},
child: const Icon(
Icons.arrow_forward,
),
),
);
}
}
According to this git link. I think you don't need to add await _controller.seekTo(Duration(seconds:_controller.value.position.inSeconds + 10). Instead add this await _controller.seekTo((await _controller.position)! + Duration(seconds: 10));. Not sure if setState is neccesory.
I am trying to put a network video from a different site in Flutter.
I have used the video_player package. I have used a future builder in which, the CircularProgressIndicator will keep running until the video is loaded. When i run the app, in the start the CircularProgressIndicator keep on running and after a few seconds it stops as if the video is loaded but it show complete blankness on the emulator. In other words the video is not loading.
After i start the app
After Loading
This is the code
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
VideoPlayerController _controller;
Future<void> _initializeVideoPlayerFuture;
#override
void initState() {
_controller = VideoPlayerController.network(
'https://ok.ru/videoembed/1616636152346');
_initializeVideoPlayerFuture = _controller.initialize();
_controller.setLooping(true);
_controller.setVolume(1.0);
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
),
body: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot){
if(snapshot.connectionState == ConnectionState.done){
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
);
} else {
return Center(
child: CircularProgressIndicator(backgroundColor: Colors.blue,
),
);
}
}
),
floatingActionButton: FloatingActionButton(
onPressed: (){
setState(() {
if(_controller.value.isPlaying){
_controller.pause();
}else{
_controller.play();
}
});
},
child: Icon(_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}
Your link for video is not a valid video link , it is a embed Url.
To Play a video from network URL use direct video URL like https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4.
Put this link in your videoController , it will working fine.
I am getting an exception thrown while using a back button after disposing of my VideoPlayerController.
I have my VideoPlayer and VideoPlayerController set up like this:
String url;
var plan;
_VideoPlayerScreenState(this.url,{this.plan});
Future<Null> OnWillPop(){
_controller.dispose();
if(plan!=null)
Navigator.push(context, MaterialPageRoute(builder: (context)=>
ListSession(plan :plan)));
else
Navigator.push(context, MaterialPageRoute(builder: (context)=>
ListMoves()));
}
VideoPlayerController _controller;
Future<void> _initializeVideoPlayerFuture;
#override
void initState() {
_controller = VideoPlayerController.network(
url,
);
// Initialize the controller and store the Future for later use.
_initializeVideoPlayerFuture = _controller.initialize();
// Use the controller to loop the video.
_controller.setLooping(true);
_controller.play();
super.initState();
}
#override
void dispose() {
print("+++++++++++++++++++++++++++++++++++++++++++");
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return WillPopScope(onWillPop: OnWillPop,child:Scaffold(
// Use a FutureBuilder to display a loading spinner while waiting for the
// VideoPlayerController to finish initializing.
body: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the VideoPlayerController has finished initialization, use
// the data it provides to limit the aspect ratio of the video.
return Center(
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
// Use the VideoPlayer widget to display the video.
child: VideoPlayer(_controller),
),
);
} else {
// If the VideoPlayerController is still initializing, show a
// loading spinner.
return Center(child: CircularProgressIndicator());
}
},
),
));
}
but when I press the back button, I get this error:
Another exception was thrown: A VideoPlayerController was used after being disposed.
How do I properly dispose of my VideoPlayerController and be able to incorporate the back button?
You can copy paste run full code below
and mark unmark Navigator.push / Navigator.pushReplacement to check effect
In your case, you do not need to dispose of controller, because controller is local to this page, you can just do _controller.pause()
You use Navigator.push go to next page means you will pop from next page
If you dispose controller and set controller to null successfully, when pop from next page, you will get an error because initState will not be called again, controller will not init again
If you use Navigator.pushReplacement, dispose will be called automatically,
You can see console show _controller.dispose in demo code.
working demo
you can see when back from ListMove page, video still can play
full code
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() => runApp(VideoPlayerApp());
class VideoPlayerApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Video Player Demo',
home: VideoPlayerScreen(),
);
}
}
class VideoPlayerScreen extends StatefulWidget {
VideoPlayerScreen({Key key}) : super(key: key);
#override
_VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
VideoPlayerController _controller;
VideoPlayerController _oldController;
Future<void> _initializeVideoPlayerFuture;
#override
void initState() {
print("initState");
// Create and store the VideoPlayerController. The VideoPlayerController
// offers several different constructors to play videos from assets, files,
// or the internet.
_controller = VideoPlayerController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',
);
// Initialize the controller and store the Future for later use.
_initializeVideoPlayerFuture = _controller.initialize();
// Use the controller to loop the video.
_controller.setLooping(true);
super.initState();
}
#override
void dispose() {
print("_controller.dispose");
// Ensure disposing of the VideoPlayerController to free up resources.
//_initializeVideoPlayerFuture = null;
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
await _controller.pause();
Navigator.push(
context, MaterialPageRoute(builder: (context) => ListMoves()));
/*Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => ListMoves()));*/
},
child: Scaffold(
appBar: AppBar(
title: Text('Butterfly Video'),
),
// Use a FutureBuilder to display a loading spinner while waiting for the
// VideoPlayerController to finish initializing.
body: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the VideoPlayerController has finished initialization, use
// the data it provides to limit the aspect ratio of the video.
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
// Use the VideoPlayer widget to display the video.
child: VideoPlayer(_controller),
);
} else {
// If the VideoPlayerController is still initializing, show a
// loading spinner.
return Center(child: CircularProgressIndicator());
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Wrap the play or pause in a call to `setState`. This ensures the
// correct icon is shown.
setState(() {
// If the video is playing, pause it.
if (_controller.value.isPlaying) {
_controller.pause();
} else {
// If the video is paused, play it.
_controller.play();
}
});
},
// Display the correct icon depending on the state of the player.
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
), // This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}
class ListMoves extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List Movies'),
),
body: Center(
child: RaisedButton(
child: Text('Launch screen'),
onPressed: () {},
),
),
);
}
}
How to set Flutter CameraPreview Size "Fullscreen"
Problem is same with this link however the solution isn't working on my phone (LG G5). Leaving a black margin around the camera preview for back camera however works fine for front camera but this time recorded video will cover a larger area than the preview video. I tried on other phones front and back camera preview works just fine but the actual recorded video covering more area problem still persists.
Edit: Problem originates from the Camera package itself not the framework for anyone out there who has a similar problem.
Further investigation and playing around with the package revealed that aspect ratio value that is returned from the package is not guaranteed to match the device's aspect ratio however works fine most of the cases.
final size = MediaQuery.of(context).size;
final deviceRatio = size.width / size.height;
return Scaffold(
key: _scaffoldKey,
body: Stack(
children: <Widget>[
controller != null
? Center(
child: Transform.scale(
scale: controller.value.aspectRatio / deviceRatio,
child: new AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: new CameraPreview(controller),
),
),
)
: Container(),
void onNewCameraSelected(CameraDescription cameraDescription) async {
if (controller != null) {
await controller.dispose();
}
controller = CameraController(
cameraDescription,
ResolutionPreset.high,
enableAudio: enableAudio,
);
// If the controller is updated then update the UI.
controller.addListener(() {
if (mounted) setState(() {});
if (controller.value.hasError) {
showInSnackBar('Camera error ${controller.value.errorDescription}');
}
});
try {
await controller.initialize();
} on CameraException catch (e) {
_showCameraException(e);
}
if (mounted) {
setState(() {
print("controller inited");
});
}
}
this is the same exact code from the docs and no use of ratio or scale found, and it works fine on every device I have including the emulator
import 'dart:async';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' show join;
import 'package:path_provider/path_provider.dart';
Future<void> main() async {
// Obtain a list of the available cameras on the device.
final cameras = await availableCameras();
// Get a specific camera from the list of available cameras.
final firstCamera = cameras.first;
runApp(
MaterialApp(
theme: ThemeData.dark(),
home: TakePictureScreen(
// Pass the appropriate camera to the TakePictureScreen widget.
camera: firstCamera,
),
),
);
}
// A screen that allows users to take a picture using a given camera.
class TakePictureScreen extends StatefulWidget {
final CameraDescription camera;
const TakePictureScreen({
Key key,
#required this.camera,
}) : super(key: key);
#override
TakePictureScreenState createState() => TakePictureScreenState();
}
class TakePictureScreenState extends State<TakePictureScreen> {
CameraController _controller;
Future<void> _initializeControllerFuture;
#override
void initState() {
super.initState();
// To display the current output from the Camera,
// create a CameraController.
_controller = CameraController(
// Get a specific camera from the list of available cameras.
widget.camera,
// Define the resolution to use.
ResolutionPreset.medium,
);
// Next, initialize the controller. This returns a Future.
_initializeControllerFuture = _controller.initialize();
}
#override
void dispose() {
// Dispose of the controller when the widget is disposed.
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Take a picture')),
// Wait until the controller is initialized before displaying the
// camera preview. Use a FutureBuilder to display a loading spinner
// until the controller has finished initializing.
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview.
return CameraPreview(_controller);
} else {
// Otherwise, display a loading indicator.
return Center(child: CircularProgressIndicator());
}
},
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.camera_alt),
// Provide an onPressed callback.
onPressed: () async {
// Take the Picture in a try / catch block. If anything goes wrong,
// catch the error.
try {
// Ensure that the camera is initialized.
await _initializeControllerFuture;
// Construct the path where the image should be saved using the
// pattern package.
final path = join(
// Store the picture in the temp directory.
// Find the temp directory using the `path_provider` plugin.
(await getTemporaryDirectory()).path,
'${DateTime.now()}.png',
);
// Attempt to take a picture and log where it's been saved.
await _controller.takePicture(path);
// If the picture was taken, display it on a new screen.
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DisplayPictureScreen(imagePath: path),
),
);
} catch (e) {
// If an error occurs, log the error to the console.
print(e);
}
},
),
);
}
}
// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatelessWidget {
final String imagePath;
const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Display the Picture')),
// The image is stored as a file on the device. Use the `Image.file`
// constructor with the given path to display the image.
body: Image.file(File(imagePath)),
);
}
}
Sorry if the question isn't that straight forward I'm just starting out. Every play video example I see through flutter examples uses a floating action button in the same class as the video player. I want to add a video player instance to my home screen and experiment with different ways to play the video (tapping on different elements, etc. I can't seem to gain access to the instance to access the controller. I'm not sure how to actually create a video player instance and then access the video controller from another place.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class VideoPlayerScreen extends StatefulWidget {
VideoPlayerScreen({Key key}) : super(key: key);
final VideoPlayerScreenState videoState = new VideoPlayerScreenState();
#override
VideoPlayerScreenState createState() => VideoPlayerScreenState();
}
class VideoPlayerScreenState extends State<VideoPlayerScreen> {
VideoPlayerController controller;
Future<void> initializeVideoPlayerFuture;
#override
void initState() {
// Create and store the VideoPlayerController. The VideoPlayerController
// offers several different constructors to play videos from assets, files,
// or the internet.
controller = VideoPlayerController.network('https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',
);
// Initialize the controller and store the Future for later use
initializeVideoPlayerFuture = controller.initialize();
// Use the controller to loop the video
controller.setLooping(true);
super.initState();
}
#override
void dispose() {
// Ensure you dispose the VideoPlayerController to free up resources
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container(
// Use a FutureBuilder to display a loading spinner while you wait for the
// VideoPlayerController to finish initializing.
child: FutureBuilder(
future: initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the VideoPlayerController has finished initialization, use
// the data it provides to limit the Aspect Ratio of the Video
return AspectRatio(
aspectRatio: controller.value.aspectRatio,
// Use the VideoPlayer widget to display the video
child: VideoPlayer(controller),
);
} else {
// If the VideoPlayerController is still initializing, show a
// loading spinner
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
//this is the button I'm calling from the app.dart file
Widget playPauseButton(VideoPlayerScreen videoPlayer){
return IconButton(
alignment: Alignment.center,
onPressed: (){
// Wrap the play or pause in a call to `setState`. This ensures the
// correct icon is shown
setState(() {
// If the video is playing, pause it.
if (videoPlayer.videoState.controller.value.isPlaying) {
videoPlayer.videoState.controller.pause();
} else {
// If the video is paused, play it
videoPlayer.videoState.controller.play();
}
});
},
icon: Icon(videoPlayer.videoState.controller.value.isPlaying ? Icons.pause: Icons.play_arrow),
);
}
you can create a class named VideoProvider and put a VideoPlayer widget inside there.
after that, all you need is create a parameter named controller and pass it to your VideoPlayer widget. controller should be a type of VideoPlayerController;
here is an example :
class MySpecificPage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MySpecificPageState();
}
}
class _MySpecificPageState extends State<MySpecificPage> {
VideoPlayerController controller;
VoidCallback listener;
#override
void initState() {
listener = () => setState(() {});
videoHandler();
super.initState();
}
void videoHandler() {
if (controller == null) {
controller = VideoPlayerController.network('https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4')
..addListener(listener)
..setVolume(0.5)
..initialize();
} else {
if (controller.value.isPlaying) {
controller.pause();
} else {
controller.play();
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Videop Provider Example'),
),
body:Container(
child: Column(
children: <Widget>[
VideoProvider(controller),
RaisedButton(
child: Text('click here to play & puase the video'),
onPressed: () {
videoHandler();
},
)
],
),
),
);
}
}
class VideoProvider extends StatelessWidget {
final VideoPlayerController controller;
VideoProvider(this.controller);
#override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: 16 / 9,
child: VideoPlayer(
controller
),
);
}
}