Audio-Video Player in Flutter
--
Task Synopsis
- We will create and Small Audio Player which pick audio files and play
- We will create an video screen which play video from network
- We will use navigator to switch screen
Let’s Start
- Add 3 dependencies in pubspec.yaml file
video_player: ^0.10.11+2 //for video player
audioplayers: ^0.14.2 //for audio player
file_picker: ^1.5.0+2 //to pick file from local storage
2. run pub get in terminal or from top bar of pubspec file
3. Create a dart file audioplayer.dart
4. import these 3 packages
import ‘package:audioplayers/audioplayers.dart’;
import ‘package:file_picker/file_picker.dart’;
import ‘package:flutter/material.dart’;
class MyAudioPlayer extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
debugShowCheckedModeBanner: false,
);
}
}
In the above code I created a Class name MyAudioPlayer and extends(inherits) StatelessWidget and create a MaterialApp
in home key I call a constructor HomePage
so next we create a class HomePage
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
In this HomePage class we extends StatefulWidget
so let me tell you what is StatefulWidget
StatefulWidget: A stateful widget is dynamic: for example, it can change its appearance in response to events triggered by user interactions or when it receives data. Checkbox , Radio , Slider , InkWell , Form , and TextField are examples of stateful widgets.
Now we Create a Private class , Private class can only be accessed in the same file
class which have one underscore in the starting of name of class is private class
class _HomePageState extends State<HomePage> {
AudioPlayer _audioPlayer = AudioPlayer();
bool isPlaying = false;
String currentTime = "00:00";
String completeTime= "00:00";
@override
void initState() {
super.initState();
_audioPlayer.onAudioPositionChanged.listen((Duration duration){
setState(() {
currentTime = duration.toString().split(".")[0];
});
});
_audioPlayer.onDurationChanged.listen((Duration duration){
setState(() {
completeTime = duration.toString().split(".")[0];
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Stack(
children: <Widget>[
Image.asset("assets/images/cover.jpg", fit: BoxFit.contain,),
Container(
width: MediaQuery.of(context).size.width*0.8,
height: 80,
margin: EdgeInsets.only(top: MediaQuery.of(context).size.height*0.7, left: MediaQuery.of(context).size.width*0.1),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(50)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
IconButton(
icon: Icon(isPlaying ? Icons.pause : Icons.play_arrow),
onPressed: (){
if(isPlaying){
_audioPlayer.pause();
setState(() {
isPlaying = false;
});
}else{
_audioPlayer.resume();
setState(() {
isPlaying = true;
});
}
},
) ,
SizedBox(width: 16,),
IconButton(
icon: Icon(Icons.stop),
onPressed: (){
_audioPlayer.stop();
setState(() {
isPlaying = false;
});
},
),
Text(currentTime, style: TextStyle(fontWeight: FontWeight.w700),),
Text(" | "),
Text(completeTime, style: TextStyle(fontWeight: FontWeight.w300),),
],
),
),
],
),
floatingActionButton: FloatingActionButton(
heroTag: "Audio",
child: Icon(Icons.audiotrack),
onPressed: () async{
String filePath = await FilePicker.getFilePath();
int status = await _audioPlayer.play(filePath, isLocal: true);
if(status == 1){
setState(() {
isPlaying = true;
});
}
},
),
);
}
}
Now we have yo manage the state so we extend State and in angular braces use that class which class(widget) state we want to manage
Next I created a private object of AudioPlayer to use the methods of audio player
Now we have to override a method named initState which initialize the state to the widget
In initState I am managing duration of my songs
Next i have created UI and Business logic of my App
Now create a dart file videoplayer.dart or you can give any name
In this file we create our video player
In video player am also using Stateful Widget
First we create a class VideoPlayerApp and extends StatelessWidget and add hot reload feature and return MaterialApp
class VideoPlayerApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'IIEC RISE',
home: VideoPlayerScreen(),
);
}
}
Now we will create videoplayer screen
class VideoPlayerScreen extends StatefulWidget {
VideoPlayerScreen({Key key}) : super(key: key);
@override
_VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}
we will Create a class VideoPlayerScreen and extends StatefulWidget in it
and create an instance of class _VideoPlayerScreenState which manages state of screen
Note: this class is not present we have to create a class for that
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
VideoPlayerController _controller;
Future<void> _initializeVideoPlayerFuture;
@override
void initState() {
_controller = VideoPlayerController.network(
'https://github.com/dineshcode97/Flutter-Data/raw/master/riseintro.MP4',
);
_initializeVideoPlayerFuture = _controller.initialize();
_controller.setLooping(true);
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Now we will create an class which manages screen state and for this we have to extends State and use that class in which we extends StatefulWidget eg VideoPlayerScreen
we have to override method initState to initialize the State
Now we will create UI and Events for this video player
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Python IIEC RISE'),
backgroundColor: Colors.red,
),
body: Column(
children: <Widget>[
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());
}
},
),
FloatingActionButton(
backgroundColor: Colors.red,
onPressed: () {
setState(() {
if (_controller.value.isPlaying) {
_controller.pause();
} else {
_controller.play();
}
});
},
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
],
),
floatingActionButton: FloatingActionButton(
heroTag: "gotoaudio",
backgroundColor: Colors.red,
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => MyAudioPlayer ()));
},
child: Icon(Icons.music_note,
),
),
);
}
}
I also created a Floating button which is used to switch from video to audio player
for this i used Navigator, Navigator is used to Navigate Screens in Flutter
Note one thing if your Video is not playing from internet then u have to give Internet permission in Mainfest file
<uses-permission android:name=”android.permission.INTERNET”/>