video-player
a video and audio player that can play from local assets, local files and network urls with the powerful controls.
how can we play videos in flutter?
there is a library directly from the flutter team simply called video_player. this library, however, is completely bare-bones. while it can play videos, it’s up to you to add video playback controls and to style it. there is a better option which comes bundled with the ui as you’d expect both on android and ios – chewie. – chewie uses the first-party video_player package behind the scenes. it only simplifies the process of video playback.
project setup
importing packages,
dependencies:
flutter:
sdk: flutter
chewie: ^0.9.7
playing videos
chewie (and video_player for that matter) can play videos from 3 sources – assets, files and network. the beauty of it is that you don’t need to write a lot of code to change the data source. switching from an asset to a network video is a matter of just a few keystrokes. let’s first take a look at assets.
- asset videos setup
assets are simply files which are readily available for your app to use. they come bundled together with your app file after you build it for release, to set up assets, simply create a folder in the root of your project and call it, for example, videos. then drag your desired video file in there.
to let flutter know about all the available assets, you have to specify them in the pubspec file. here i added all the dependencies needed in the project.
dependencies:
flutter:
sdk: flutter
# the following adds the cupertino icons font to your application.
# use with the cupertinoicons class for ios style icons.
cupertino_icons: ^0.1.3
chewie: ^0.9.10
file_picker: ^1.13.0+1
audioplayers: ^0.15.1
fluttertoast: ^7.0.2
using the chewie widget
now comes the time to start playing videos. for that chewie provides its own widget which is, as i’ve already mentioned, only a wrapper on top of the videoplayer which comes directly from the flutter team.
because we want to play multiple videos displayed in a listview, it’s going to be the best to put all of the video-playing related things into it’s own widget. also, because video player resources need to be released, you need to create a statefulwidget to get hold of the dispose() method.
lets create videos_list.dart,
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class videoslist extends statefulwidget {
final videoplayercontroller videoplayercontroller;
final bool looping;
const videoslist(
{key key, @required this.videoplayercontroller, this.looping})
: super(key: key);
@override
_videosliststate createstate() => _videosliststate();
}
class _videosliststate extends state<videoslist> {
chewiecontroller videoscontroller;
@override
void initstate() {
super.initstate();
videoscontroller = chewiecontroller(
videoplayercontroller: widget.videoplayercontroller,
aspectratio: 16 / 9,
autoinitialize: true,
looping: widget.looping,
errorbuilder: (context, errormessage) {
return center(child: progressbar()
);
},
);
}
widget progressbar() {
return circularprogressindicator();
}
@override
widget build(buildcontext context) {
return padding(
padding: const edgeinsets.all(8.0),
child: chewie(
controller: videoscontroller,
),
);
}
@override
void dispose() {
super.dispose();
// important to dispose of all the used resources
// widget.videoplayercontroller.dispose();
videoscontroller.dispose();
}
}
to play the videos inside a listview, we don’t need to do a lot of additional work. with all of the chewie stuff in its own separate widget, let’s create a myhomepage statelesswidget.
in main.dart, added all the necessary components needed in the project
import 'package:audioplayers/audioplayers.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:video_app/videos_list.dart';
import 'package:video_player/video_player.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() => runapp(myapp());
class myapp extends statelesswidget {
@override
widget build(buildcontext context) {
return materialapp(
home: myhomepage(),
debugshowcheckedmodebanner: false,
);
}
}
int status = 0;
audioplayer player = audioplayer();
class myhomepage extends statelesswidget {
@override
widget build(buildcontext context) {
return scaffold(
backgroundcolor: colors.purple[50],
appbar: appbar(
leading: icon(
icons.play_circle_filled,
size: 45,
),
backgroundcolor: colors.deeppurple,
title: text("music player"),
actions: <widget>[
iconbutton(icon: icon(icons.next_week), onpressed: () {}),
iconbutton(
icon: icon(icons.new_releases),
onpressed: () {
fluttertoast.showtoast(
msg: "new features coming soon!",
toastlength: toast.length_long,
gravity: toastgravity.bottom,
timeinsecforiosweb: 1,
backgroundcolor: colors.deeppurple,
textcolor: colors.white,
fontsize: 16.0);
}),
],
),
body: stack(children: <widget>[
listview(
children: <widget>[
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/ansible.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/specialist_in_python.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/ansiblepro.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.network(
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/bigbuckbunny.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/openshift.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/flutter.mp4',
),
looping: true,
),
],
),
]),
floatingactionbutton: floatingactionbutton(
child: icon(icons.audiotrack),
elevation: 15,
backgroundcolor: colors.deeppurple,
onpressed: () async {
if (status == 1) {
status = await player.stop();
status = 0;
} else {
string filepath = await filepicker.getfilepath();
status = await player.play(filepath, islocal: true);
//also can be played from the assets...
//but users must have choices so local file is used!!
}
},
));
}
}
here we added some video from assets and some from network
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/ansible.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/specialist_in_python.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/ansiblepro.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.network(
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/bigbuckbunny.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/openshift.mp4',
),
looping: true,
),
videoslist(
videoplayercontroller: videoplayercontroller.asset(
'videos/flutter.mp4',
),
looping: true,
),
for playing audio
you have two options
we use audioplayers plugin.
1) it is easy to implement, but here in this project we used defferent approch to audioplayer. as i wanted to make this app a singal page app, i did not use intent foe switching between two activities, foe playing and stoping audio i used singal floating button with that level of capability, here is the code snippet for that,
floatingactionbutton: floatingactionbutton(
child: icon(icons.audiotrack),
elevation: 15,
backgroundcolor: colors.deeppurple,
onpressed: () async {
if (status == 1) {
status = await player.stop();
status = 0;
} else {
string filepath = await filepicker.getfilepath();
status = await player.play(filepath, islocal: true);
//also can be played from the assets...
//but users must have choices so local file is used!!
}
},
)
2) here i implemented dedicated ui for audio and it’s functionalities like play, pause and stop buttons with duration with it,
for audio poster for now we are using static images, add your images in images root nfolder like this,
and also add assets path to your pubspec.yml file,
for implementing audio functionalities and ui refere audio.dart,
import 'package:audioplayers/audioplayers.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
myapp() {
return materialapp(
home: homepage(),
debugshowcheckedmodebanner: false,
);
}
class homepage extends statefulwidget {
@override
_homepagestate createstate() => _homepagestate();
}
class _homepagestate extends state<homepage> {
audioplayer player = audioplayer();
bool isplaying = false;
string currenttime = "0:00:00";
string completetime = "0:00:00";
@override
void initstate() {
super.initstate();
player.onaudiopositionchanged.listen((duration duration) {
setstate(() {
currenttime = duration.tostring().split(".")[0];
});
});
player.ondurationchanged.listen((duration duration) {
setstate(() {
completetime = duration.tostring().split(".")[0];
});
});
}
widget build(buildcontext context) {
return scaffold(
body: container(
width: double.infinity,
height: double.infinity,
color: colors.bluegrey[200],
child: column(
children: <widget>[
card(
shadowcolor: colors.deeppurple[900],
elevation: 20,
margin: edgeinsets.only(top: 40, left: 30, right: 30),
child: image.asset("images/wallhaven.jpg"),
),
container(
margin: edgeinsets.only(top: 50),
width: 240,
height: 50,
decoration: boxdecoration(
color: colors.white,
borderradius: borderradius.circular(80),
),
child: row(
// mainaxisalignment: mainaxisalignment.spacearound,
// mainaxissize: mainaxissize.max,
// mainaxisalignment: mainaxisalignment.center,
children: <widget>[
iconbutton(
icon: icon(
isplaying
? icons.pause_circle_filled
: icons.play_circle_filled,
color: colors.black,
size: 30,
),
onpressed: () {
if (isplaying) {
player.pause();
setstate(() {
isplaying = false;
});
} else {
player.resume();
setstate(() {
isplaying = true;
});
}
}),
iconbutton(
icon: icon(
icons.stop,
color: colors.black,
size: 25,
),
onpressed: () {
player.stop();
setstate(() {
isplaying = false;
});
},
),
text(
" " + currenttime,
style: textstyle(fontweight: fontweight.w700),
),
text(" | "),
text(
completetime,
style: textstyle(fontweight: fontweight.w300),
),
],
)),
],
),
),
floatingactionbutton: floatingactionbutton(
child: icon(icons.audiotrack),
elevation: 10,
backgroundcolor: colors.deeppurple,
onpressed: () async {
string filepath = await filepicker.getfilepath();
int status = await player.play(filepath, islocal: true);
if (status == 1) {
setstate(() {
isplaying = true;
});
}
},
),
);
}
}
we are using audiocache streams for duration and position for that have to subscribe to the streams,
player.onaudiopositionchanged.listen((duration duration) {
setstate(() {
currenttime = duration.tostring().split(".")[0];
});
});
player.ondurationchanged.listen((duration duration) {
setstate(() {
completetime = duration.tostring().split(".")[0];
});
});
our audio ui will look like this,
chewie is a flutter package aimed at simplifying the process of playing videos. instead of you having to deal with start, stop, and pause buttons, doing the overlay to display the progress of the video, chewie does these things for you.
here is the final output of our project
click here for sounded output.
future features to added
- can add audio/video from network url(user input).
- add the play/pause and duration in minutes to audio part.
- share the screenshots of the app.
- notification of what you are currently playing.
Comments are closed.