better player
better video player for flutter, with multiple configuration options. solving typical use cases!
introduction
this plugin is based on chewie. chewie is awesome plugin and works well in many cases. better player is a continuation of ideas introduced in chewie. better player fix common bugs, adds more configuration options and solves typical use cases.
features:
✔️ fixed common bugs
✔️ added advanced configuration options
✔️ refactored player controls
✔️ playlist support
✔️ video in listview support
✔️ subtitles support: (formats: srt, webvtt with html tags support; subtitles from hls; multiple subtitles for video)
✔️ http headers support
✔️ boxfit of video support
✔️ playback speed support
✔️ hls support (track, subtitles selection)
✔️ alternative resolution support
✔️ cache support
✔️ notifications support
✔️ … and much more!
install
- add this to your pubspec.yaml file:
dependencies:
better_player: ^0.0.44
- install it
$ flutter packages get
- import it
import 'package:better_player/better_player.dart';
general usage
check example project which shows how to use better player in different scenarios.
basic usage
there are 2 basic methods which you can use to setup better player:
betterplayer.network(url, configuration)
betterplayer.file(url, configuration)
there methods setup basic configuration for you and allows you to start using player in few seconds.
here is an example:
@override
widget build(buildcontext context) {
return scaffold(
appbar: appbar(
title: text("example player"),
),
body: aspectratio(
aspectratio: 16 / 9,
child: betterplayer.network(
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/forbiggerblazes.mp4",
betterplayerconfiguration: betterplayerconfiguration(
aspectratio: 16 / 9,
),
),
),
);
}
in this example, we’re just showing video from url with aspect ratio = 16/9.
better player has many more configuration options which are presented below.
normal usage
create betterplayerdatasource and betterplayercontroller. you should do it in initstate:
betterplayercontroller _betterplayercontroller;
@override
void initstate() {
super.initstate();
betterplayerdatasource betterplayerdatasource = betterplayerdatasource(
betterplayerdatasourcetype.network,
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/bigbuckbunny.mp4");
_betterplayercontroller = betterplayercontroller(
betterplayerconfiguration(),
betterplayerdatasource: betterplayerdatasource);
}
create betterplayer widget wrapped in aspectratio widget:
@override
widget build(buildcontext context) {
return aspectratio(
aspectratio: 16 / 9,
child: betterplayer(
controller: _betterplayercontroller,
),
);
}
playlist
to use playlist, you need to create dataset with multiple videos:
list<betterplayerdatasource> createdataset() {
list datasourcelist = list<betterplayerdatasource>();
datasourcelist.add(
betterplayerdatasource(
betterplayerdatasourcetype.network,
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/forbiggerblazes.mp4",
),
);
datasourcelist.add(
betterplayerdatasource(betterplayerdatasourcetype.network,
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/bigbuckbunny.mp4"),
);
datasourcelist.add(
betterplayerdatasource(betterplayerdatasourcetype.network,
"http://sample.vodobox.com/skate_phantom_flex_4k/skate_phantom_flex_4k.m3u8"),
);
return datasourcelist;
}
then create betterplayerplaylist:
@override
widget build(buildcontext context) {
return aspectratio(
aspectratio: 16 / 9,
child: betterplayerplaylist(
betterplayerconfiguration: betterplayerconfiguration(),
betterplayerplaylistconfiguration: const betterplayerplaylistconfiguration(),
betterplayerdatasourcelist: datasourcelist),
);
}
betterplayerlistviewplayer
betterplayerlistviewplayer will auto play/pause video once video is visible on screen with playfraction. playfraction describes percent of video that must be visibile to play video. if playfraction is 0.8 then 80% of video height must be visible on screen to auto play video
@override
widget build(buildcontext context) {
return aspectratio(
aspectratio: 16 / 9,
child: betterplayerlistvideoplayer(
betterplayerdatasource(
betterplayerdatasourcetype.network, videolistdata.videourl),
key: key(videolistdata.hashcode.tostring()),
playfraction: 0.8,
),
);
}
you can control betterplayerlistviewplayer with betterplayerlistviewplayercontroller. you need to pass
betterplayerlistviewplayercontroller to betterplayerlistvideoplayer. see more in example app.
subtitles
subtitles can be configured from 3 different sources: file, network and memory. subtitles source is passed in betterplayerdatasource:
network subtitles:
var datasource = betterplayerdatasource(
betterplayerdatasourcetype.network,
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/forbiggerblazes.mp4",
subtitles: betterplayersubtitlessource.single(
type: betterplayersubtitlessourcetype.network,
url:
"https://dl.dropboxusercontent.com/s/71nzjo2ux3evxqk/example_subtitles.srt"),
);
file subtitles:
var datasource = betterplayerdatasource(
betterplayerdatasourcetype.file,
"${directory.path}/testvideo.mp4",
subtitles: betterplayersubtitlessource.single(
type: betterplayersubtitlessourcetype.file,
url: "${directory.path}/example_subtitles.srt",
),
);
you can pass multiple subtitles for one video:
var datasource = betterplayerdatasource(
betterplayerdatasourcetype.network,
"https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8",
livestream: false,
usehlssubtitles: true,
hlstracknames: ["low quality", "not so low quality", "medium quality"],
subtitles: [
betterplayersubtitlessource(
type: betterplayersubtitlessourcetype.network,
name: "en",
urls: [
"https://dl.dropboxusercontent.com/s/71nzjo2ux3evxqk/example_subtitles.srt"
],
),
betterplayersubtitlessource(
type: betterplayersubtitlessourcetype.network,
name: "de",
urls: [
"https://dl.dropboxusercontent.com/s/71nzjo2ux3evxqk/example_subtitles.srt"
],
),
],
);
betterplayerconfiguration
you can provide configuration to your player when creating betterplayercontroller.
var betterplayerconfiguration = betterplayerconfiguration(
autoplay: true,
looping: true,
fullscreenbydefault: true,
);
possible configuration options:
/// play the video as soon as it's displayed
final bool autoplay;
/// start video at a certain position
final duration startat;
/// whether or not the video should loop
final bool looping;
/// weather or not to show the controls when initializing the widget.
final bool showcontrolsoninitialize;
/// when the video playback runs into an error, you can build a custom
/// error message.
final widget function(buildcontext context, string errormessage) errorbuilder;
/// the aspect ratio of the video. important to get the correct size of the
/// video!
///
/// will fallback to fitting within the space allowed.
final double aspectratio;
/// the placeholder is displayed underneath the video before it is initialized
/// or played.
final widget placeholder;
/// should the placeholder be shown until play is pressed
final bool showplaceholderuntilplay;
/// placeholder position of player stack. if false, then placeholder will be
/// displayed on the bottom, so user need to hide it manually. default is
/// true.
final bool placeholderontop;
/// a widget which is placed between the video and the controls
final widget overlay;
/// defines if the player will start in fullscreen when play is pressed
final bool fullscreenbydefault;
/// defines if the player will sleep in fullscreen or not
final bool allowedscreensleep;
/// defines aspect ratio which will be used in fullscreen
final double fullscreenaspectratio;
/// defines the set of allowed device orientations on entering fullscreen
final list<deviceorientation> deviceorientationsonfullscreen;
/// defines the system overlays visible after exiting fullscreen
final list<systemuioverlay> systemoverlaysafterfullscreen;
/// defines the set of allowed device orientations after exiting fullscreen
final list<deviceorientation> deviceorientationsafterfullscreen;
/// defines a custom routepagebuilder for the fullscreen
final betterplayerroutepagebuilder routepagebuilder;
/// defines a event listener where video player events will be send
final function(betterplayerevent) eventlistener;
///defines subtitles configuration
final betterplayersubtitlesconfiguration subtitlesconfiguration;
///defines controls configuration
final betterplayercontrolsconfiguration controlsconfiguration;
///defines fit of the video, allows to fix video stretching, see possible
///values here: https://api.flutter.dev/flutter/painting/boxfit-class.html
final boxfit fit;
///defines rotation of the video in degrees. default value is 0. can be 0, 90, 180, 270.
///angle will rotate only video box, controls will be in the same place.
final double rotation;
///defines function which will react on player visibility changed
final function(double visibilityfraction) playervisibilitychangedbehavior;
///defines translations used in player. if null, then default english translations
///will be used.
final list<betterplayertranslations> translations;
///defines if player should auto detect full screen device orientation based
///on aspect ratio of the video. if aspect ratio of the video is < 1 then
///video will played in full screen in portrait mode. if aspect ratio is >= 1
///then video will be played horizontally. if this parameter is true, then
///[deviceorientationsonfullscreen] and [fullscreenaspectratio] value will be
/// ignored.
final bool autodetectfullscreendeviceorientation;
///defines flag which enables/disables lifecycle handling (pause on app closed,
///play on app resumed). default value is true.
final bool handlelifecycle;
///defines flag which enabled/disabled auto dispose on betterplayer dispose.
///default value is true.
final bool autodispose;
betterplayersubtitlesconfiguration
you can provide subtitles configuration with this class. you should put betterplayersubtitlesconfiguration in betterplayerconfiguration.
var betterplayerconfiguration = betterplayerconfiguration(
subtitlesconfiguration: betterplayersubtitlesconfiguration(
fontsize: 20,
fontcolor: colors.green,
),
);
possible configuration options:
///subtitle font size
final double fontsize;
///subtitle font color
final color fontcolor;
///enable outline (border) of the text
final bool outlineenabled;
///color of the outline stroke
final color outlinecolor;
///outline stroke size
final double outlinesize;
///font family of the subtitle
final string fontfamily;
///left padding of the subtitle
final double leftpadding;
///right padding of the subtitle
final double rightpadding;
///bottom padding of the subtitle
final double bottompadding;
///alignment of the subtitle
final alignment alignment;
///background color of the subtitle
final color backgroundcolor;
///subtitles selected by default, without user interaction
final bool selectedbydefault;
betterplayercontrolsconfiguration
configuration for player gui. you should pass this configuration to betterplayerconfiguration.
var betterplayerconfiguration = betterplayerconfiguration(
controlsconfiguration: betterplayercontrolsconfiguration(
textcolor: colors.black,
iconscolor: colors.black,
),
);
///color of the control bars
final color controlbarcolor;
///color of texts
final color textcolor;
///color of icons
final color iconscolor;
///icon of play
final icondata playicon;
///icon of pause
final icondata pauseicon;
///icon of mute
final icondata muteicon;
///icon of unmute
final icondata unmuteicon;
///icon of fullscreen mode enable
final icondata fullscreenenableicon;
///icon of fullscreen mode disable
final icondata fullscreendisableicon;
///cupertino only icon, icon of skip
final icondata skipbackicon;
///cupertino only icon, icon of forward
final icondata skipforwardicon;
///flag used to enable/disable fullscreen
final bool enablefullscreen;
///flag used to enable/disable mute
final bool enablemute;
///flag used to enable/disable progress texts
final bool enableprogresstext;
///flag used to enable/disable progress bar
final bool enableprogressbar;
///flag used to enable/disable play-pause
final bool enableplaypause;
///flag used to enable skip forward and skip back
final bool enableskips;
///progress bar played color
final color progressbarplayedcolor;
///progress bar circle color
final color progressbarhandlecolor;
///progress bar buffered video color
final color progressbarbufferedcolor;
///progress bar background color
final color progressbarbackgroundcolor;
///time to hide controls
final duration controlshidetime;
///parameter used to build custom controls
final widget function(betterplayercontroller controller)
customcontrolsbuilder;
///parameter used to change theme of the player
final betterplayertheme playertheme;
///flag used to show/hide controls
final bool showcontrols;
///flag used to show controls on init
final bool showcontrolsoninitialize;
///control bar height
final double controlbarheight;
///live text color;
final color livetextcolor;
///flag used to show/hide overflow menu which contains playback, subtitles,
///qualities options.
final bool enableoverflowmenu;
///flag used to show/hide playback speed
final bool enableplaybackspeed;
///flag used to show/hide subtitles
final bool enablesubtitles;
///flag used to show/hide qualities
final bool enablequalities;
///custom items of overflow menu
final list<betterplayeroverflowmenuitem> overflowmenucustomitems;
///icon of the overflow menu
final icondata overflowmenuicon;
///icon of the playback speed menu item from overflow menu
final icondata playbackspeedicon;
///icon of the subtitles menu item from overflow menu
final icondata subtitlesicon;
///icon of the qualities menu item from overflow menu
final icondata qualitiesicon;
///color of overflow menu icons
final color overflowmenuiconscolor;
///time which will be used once user uses rewind and forward
final int skipstimeinmilliseconds;
betterplayerplaylistconfiguration
configure your playlist. pass this object to betterplayerplaylist
var betterplayerplaylistconfiguration = betterplayerplaylistconfiguration(
loopvideos: false,
nextvideodelay: duration(milliseconds: 5000),
);
possible configuration options:
///how long user should wait for next video
final duration nextvideodelay;
///should videos be looped
final bool loopvideos;
betterplayerdatasource
define source for one video in your app. there are 3 types of data sources:
- network – data source which uses url to play video from external resources
- file – data source which uses url to play video from internal resources
- memory – data source which uses list of bytes to play video from memory
var datasource = betterplayerdatasource(
betterplayerdatasourcetype.network,
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/forbiggerblazes.mp4",
subtitles: betterplayersubtitlessource(
type: betterplayersubtitlessourcetype.file,
url: "${directory.path}/example_subtitles.srt",
),
headers: {"header":"my_custom_header"}
);
you can use type specific factories to build your data source.
use betterplayerdatasource.network to build network data source, betterplayerdatasource.file to build file data source and betterplayerdatasource.memory
to build memory data source.
possible configuration options:
///type of source of video
final betterplayerdatasourcetype type;
///url of the video
final string url;
///subtitles configuration
///you can pass here multiple subtitles
final list<betterplayersubtitlessource> subtitles;
///flag to determine if current data source is live stream
final bool livestream;
/// custom headers for player
final map<string, string> headers;
///should player use hls subtitles. default is true.
final bool usehlssubtitles;
///should player use hls tracks
final bool usehlstracks;
///list of strings that represents tracks names.
///if empty, then better player will choose name based on track parameters
final list<string> hlstracknames;
///optional, alternative resolutions for non-hls video. used to setup
///different qualities for video.
///data should be in given format:
///{"360p": "url", "540p": "url2" }
final map<string, string> resolutions;
///optional cache configuration, used only for network data sources
final betterplayercacheconfiguration cacheconfiguration;
betterplayercacheconfiguration
define cache configuration for given data source. cache works only for network data sources.
///enable cache for network data source
final bool usecache;
/// the maximum cache size to keep on disk in bytes.
/// android only option.
final int maxcachesize;
/// the maximum size of each individual file in bytes.
/// android only option.
final int maxcachefilesize;
betterplayersubtitlessource
define source of subtitles in your video:
var subtitles = betterplayersubtitlessource(
type: betterplayersubtitlessourcetype.file,
url: "${directory.path}/example_subtitles.srt",
);
possible configuration options:
///source type
final betterplayersubtitlessourcetype type;
///url of the subtitles, used with file or network subtitles
final string url;
///content of subtitles, used when type is memory
final string content;
betterplayertranslations
you can provide translations for different languages. you need to pass list of betterplayertranslations to
the betterplayerconfiguration. here is an example:
translations: [
betterplayertranslations(
languagecode: "language_code for example pl",
generaldefaulterror: "translated text",
generalnone: "translated text",
generaldefault: "translated text",
playlistloadingnextvideo: "translated text",
controlslive: "translated text",
controlsnextvideoin: "translated text",
overflowmenuplaybackspeed: "translated text",
overflowmenusubtitles: "translated text",
overflowmenuquality: "translated text",
),
betterplayertranslations(
languagecode: "other language for example cz",
generaldefaulterror: "translated text",
generalnone: "translated text",
generaldefault: "translated text",
playlistloadingnextvideo: "translated text",
controlslive: "translated text",
controlsnextvideoin: "translated text",
overflowmenuplaybackspeed: "translated text",
overflowmenusubtitles: "translated text",
overflowmenuquality: "translated text",
),
],
there are 4 pre build in languages: en, pl, zh (chinese simplified), hi (hindi). if you didn’t provide
any translation then en translations will be used or any of the pre build in translations, only if it’s
match current user locale.
you need to setup localizations in your app first to make it work. here’s how you can do that:
https://flutter.dev/docs/development/accessibility-and-localization/internationalization
listen to video events
you can listen to video player events like:
initialized,
play,
pause,
seekto,
openfullscreen,
hidefullscreen,
setvolume,
progress,
finished,
exception,
controlsvisible,
controlshidden,
setspeed,
changedsubtitles,
changedtrack,
changedplayervisibility,
changedresolution
after creating betterplayercontroller you can add event listener this way:
_betterplayercontroller.addeventslistener((event){
print("better player event: ${event.betterplayereventtype}");
});
your event listener will ne auto-disposed on dispose time 🙂
change player behavior if player is not visible
you can change player behavior if player is not visible by using playervisibilitychangedbehavior option in betterplayerconfiguration.
here is an example for player used in list:
void onvisibilitychanged(double visiblefraction) async {
bool isplaying = await _betterplayercontroller.isplaying();
bool initialized = _betterplayercontroller.isvideoinitialized();
if (visiblefraction >= widget.playfraction) {
if (widget.autoplay && initialized && !isplaying && !_isdisposing) {
_betterplayercontroller.play();
}
} else {
if (widget.autopause && initialized && isplaying && !_isdisposing) {
_betterplayercontroller.pause();
}
}
}
player behavior works in the basis of visibilitydetector (it uses visibilityfraction, which is value from 0.0 to 1.0 that describes how much given widget is on the viewport). so if value 0.0, player is not visible, so we need to pause the video. if the visibilityfraction is 1.0, we need to play it again.
pass multiple resolutions of the video
you can setup video with different resolutions. use resolutions parameter in data source. this should be used
only for normal videos (non-hls) to setup different qualities of the original video.
var datasource = betterplayerdatasource(betterplayerdatasourcetype.network,
"https://file-examples-com.github.io/uploads/2017/04/file_example_mp4_480_1_5mg.mp4",
resolutions: {
"low":
"https://file-examples-com.github.io/uploads/2017/04/file_example_mp4_480_1_5mg.mp4",
"medium":
"https://file-examples-com.github.io/uploads/2017/04/file_example_mp4_640_3mg.mp4",
"large":
"https://file-examples-com.github.io/uploads/2017/04/file_example_mp4_1280_10mg.mp4",
"extra_large":
"https://file-examples-com.github.io/uploads/2017/04/file_example_mp4_1920_18mg.mp4"
});
setup player notification
to setup player notification use notificationconfiguration in betterplayerdatasource.
betterplayerdatasource datasource = betterplayerdatasource(
betterplayerdatasourcetype.network,
constants.elephantdreamvideourl,
notificationconfiguration: betterplayernotificationconfiguration(
shownotification: true,
title: "elephant dream",
author: "some author",
imageurl:"https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/african_bush_elephant.jpg/1200px-african_bush_elephant.jpg",
),
);
there are 3 majors parameters here:
title – name of the resource, shown in first line
author – author of the resource, shown in second line
imageurl – image of the resource (optional). can be both link to external image or internal file.
if shownotification is set as true and no title and author is provided, then empty notification will be
displayed.
user can control the player with notification buttons (i.e. play/pause, seek). when notification feature
is used when there are more players at the same time, then last player will be used. notification will
be shown after play for the first time.
to play resource after leaving the app, set handlelifecycle as false in your betterplayerconfiguration.
important note for android:
you need to add special service in android native code. service will simply destroy all remaining notifications.
this service need to be used to handle situation when app is killed without proper player destroying.
check betterplayerservice in example project to see how to add this service to your app.
https://github.com/jhomlala/betterplayer/blob/feature/player_notifications/example/android/app/src/main/kotlin/com/jhomlala/better_player_example/betterplayerservice.kt
here is an example of player with notification: https://github.com/jhomlala/betterplayer/blob/feature/player_notifications/example/lib/pages/notification_player_page.dart
add custom element to overflow menu
you can use betterplayercontrolsconfiguration to add custom element to the overflow menu:
controlsconfiguration: betterplayercontrolsconfiguration(
overflowmenucustomitems: [
betterplayeroverflowmenuitem(
icons.account_circle_rounded,
"custom element",
() => print("click!"),
)
],
),
enable/disable controls (always hidden if false)
betterplayercontroller.setcontrolsenabled(false);
set overridden aspect ratio. if passed overriddenaspectratio will be used instead of aspectratio.
if null then aspectratio from betterplayerconfiguration will be used.
betterplayercontroller.setoverriddenaspectratio(1.0);
overridden duration
if overridden duration is set then video player will play video until this duration.
betterplayerdatasource datasource = betterplayerdatasource(
betterplayerdatasourcetype.network,
constants.elephantdreamvideourl,
///play only 10 seconds of this video.
overriddenduration: duration(seconds: 10),
);
(ios only) add into info.plist (to support fullscreen rotation):
<key>uisupportedinterfaceorientations</key>
<array>
<string>uiinterfaceorientationportrait</string>
<string>uiinterfaceorientationlandscapeleft</string>
<string>uiinterfaceorientationlandscaperight</string>
</array>
Comments are closed.