Flutter provides excellent support for multimedia applications, allowing you to easily integrate video and audio playback into your apps. Whether you’re building a video streaming app, a music player, or just want to add some audio-visual elements to enhance the user experience, Flutter’s robust ecosystem offers the tools you need. This article dives into working with video and audio playback in Flutter, providing detailed code samples and explanations.
Understanding Video and Audio Playback in Flutter
Flutter offers a comprehensive set of plugins to handle video and audio playback. Key among these are:
video_player: For playing video files from local storage or network URLs.chewie: A Flutter package providing customizable video playback widgets (based onvideo_player).audioplayers: For playing audio files with support for local files, network streams, and more.
Let’s explore these plugins and how to use them effectively.
Part 1: Video Playback with video_player
The video_player plugin provides the core functionality for video playback in Flutter. It supports both local and network video sources.
Step 1: Add Dependency
Add the video_player dependency to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
video_player: ^2.8.1
Run flutter pub get to install the dependency.
Step 2: Initialize the Video Player
Create a VideoPlayerController to manage video playback.
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class VideoPlayerScreen extends StatefulWidget {
@override
_VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State {
late VideoPlayerController _controller;
late Future _initializeVideoPlayerFuture;
@override
void initState() {
super.initState();
// For local video file:
// _controller = VideoPlayerController.asset('assets/videos/my_video.mp4');
// For network video URL:
_controller = VideoPlayerController.networkUrl(Uri.parse(
'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',
));
_initializeVideoPlayerFuture = _controller.initialize();
_controller.setLooping(true);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Video Player Example'),
),
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(),
);
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
if (_controller.value.isPlaying) {
_controller.pause();
} else {
_controller.play();
}
});
},
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}
Step 3: Displaying the Video
The VideoPlayer widget displays the video. It uses the VideoPlayerController to control playback. We wrap the VideoPlayer in an AspectRatio widget to maintain the video’s aspect ratio. A FloatingActionButton toggles between play and pause.
Part 2: Enhanced Video Playback with chewie
While video_player offers basic functionality, chewie provides a more user-friendly, feature-rich experience. Chewie is built on top of video_player and adds customizable controls, full-screen support, and more.
Step 1: Add Dependency
Include the chewie dependency in your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
video_player: ^2.8.1
chewie: ^1.7.0
Run flutter pub get to install the dependency.
Step 2: Implementing Chewie
Create a ChewieController using the VideoPlayerController:
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
class ChewieVideoPlayer extends StatefulWidget {
@override
_ChewieVideoPlayerState createState() => _ChewieVideoPlayerState();
}
class _ChewieVideoPlayerState extends State {
late VideoPlayerController _videoPlayerController;
ChewieController? _chewieController;
@override
void initState() {
super.initState();
_videoPlayerController = VideoPlayerController.networkUrl(
Uri.parse('https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4'),
);
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController,
autoPlay: true,
looping: true,
// Additional controls
aspectRatio: 16 / 9,
autoInitialize: true,
errorBuilder: (context, errorMessage) {
return Center(
child: Text(
errorMessage,
style: TextStyle(color: Colors.white),
),
);
},
);
}
@override
void dispose() {
_videoPlayerController.dispose();
_chewieController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chewie Video Player'),
),
body: Center(
child: _chewieController != null
? Chewie(
controller: _chewieController!,
)
: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 20),
Text('Loading Video...'),
],
),
),
);
}
}
Step 3: Configuring ChewieController
Key properties of ChewieController:
videoPlayerController: TheVideoPlayerControllerinstance.autoPlay: Automatically starts the video.looping: Loops the video.aspectRatio: Defines the aspect ratio of the video player.autoInitialize: Automatically initializes theVideoPlayerController.errorBuilder: Customizes the error display.
Part 3: Audio Playback with audioplayers
For audio playback in Flutter, the audioplayers plugin is a great choice. It supports various audio formats and offers features like background playback, looping, and controlling playback speed.
Step 1: Add Dependency
Include the audioplayers dependency in your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
audioplayers: ^5.2.1
Run flutter pub get to install the dependency.
Step 2: Basic Audio Playback
Implement a simple audio player using AudioPlayer:
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
class AudioPlayerScreen extends StatefulWidget {
@override
_AudioPlayerScreenState createState() => _AudioPlayerScreenState();
}
class _AudioPlayerScreenState extends State {
final AudioPlayer audioPlayer = AudioPlayer();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Audio Player Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
// Play from a remote URL
await audioPlayer.play(AssetSource('audio/sound.mp3'));
},
child: Text('Play'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
await audioPlayer.pause();
},
child: Text('Pause'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
await audioPlayer.stop();
},
child: Text('Stop'),
),
],
),
),
);
}
@override
void dispose() {
audioPlayer.dispose();
super.dispose();
}
}
Ensure you have an audio file named sound.mp3 in your assets folder and specify it in your pubspec.yaml:
assets:
- assets/audio/
Step 3: More Control
AudioPlayer offers various control options like setting volume, playback rate, and managing playback state.
// Set volume
audioPlayer.setVolume(0.5); // Range: 0.0 to 1.0
// Set playback rate
audioPlayer.setPlaybackRate(1.2); // Higher values increase speed
// Listen for playback state changes
audioPlayer.onPlayerStateChanged.listen((PlayerState s) => print('Current state: $s'));
Conclusion
Flutter provides a versatile platform for building multimedia applications with robust video and audio playback support. The video_player and chewie plugins offer powerful video playback capabilities, while audioplayers delivers comprehensive audio management. By integrating these plugins and leveraging the provided code samples, developers can create engaging and dynamic Flutter apps with seamless multimedia experiences.