A Complete Guide to Create Video-Streaming App with Flutter (Using MUX)

Video Streaming App With flutter

Video streaming has turned into an inevitable trend that rules almost every popular app nowadays. Be it the Instagram Reels or Tik Tok; everyone is going gaga over such content. And, app makers are milking huge profits from this new trend of video streaming. 

But no matter how amazingly video streaming hooks the watchers, Flutter developers use blood, sweat, and tears to handle the back-end’s technicalities to deliver what we see. 

This guide focuses on two major things, which are:

  1. CREATING FLUTTER APP (USING MUX) FOR VIDEO STREAMING
  2. HOW TO PLAY AND PAUSE VIDEOS IN FLUTTER APPS 

Let’s begin! 

  1. CREATING FLUTTER APP (USING MUX) FOR VIDEO STREAMING
Flutter Apps

What are the Main Steps Involved in Video Streaming?

  1. Encoding and decoding the video 
  2. Handling video database storage 
  3. Multiple Video Format Support 
  4. Distribution 

Since We Are Creating an App with MUX, let’s see what Mux is:

What is MUX? 

MUX is an API-based video streaming service to handle the encoding and decoding of a video and distribute it to the users. In addition, using MUX lets you enjoy certain other features like GIFs, watermarks, subtitles, and thumbnails. Besides, MUX uses the data tracking API that helps in managing how exactly the video streaming has performed. However, MUX doesn’t take the responsibility of storing the video content. And, that’s why you will have to offer a URL where the video is stored. 

Getting Started with MUX

  1. Go to https://mux.com/ and create your account.
  2. Once done, click on ‘Dashboard.’
  3. Add a video by visiting the ‘add a video file’ section to run the post request. 
  4.  Video will be stored in the assets section. 
  5. Generate API access token and enter the necessary details before clicking on Generate Token ID and Token Secret for API authentication. 
  6. Save these files in a private folder.

Essential Plugins to Build the App 

  1. Dio – A powerful HTTP client for Dart that supports Global configuration, Request Cancellation, Timeout, Downloading, FormData, and Interceptors. 
  2. Intl – Offers internationalization and localization facilities like plurals and genders, bidirectional text, number and date formatting and phrasing, and message translation. 
  3. Video Player – Flutter plugin for web, Android, and iOS to playback video on a Widget surface. 

How to Build the Backend?

Video Streaming apps with flutter

Start by designing the backend of the app, followed by working on UI. Next, flutter developers focus on building a simple API server to send requests to Mux. You can write basic API server code in node.js.

Inside the root folder, you will have to create a file named .env with the following content.

MUX_TOKEN_ID=”<mux_token_id>”

MUX_TOKEN_SECRET=”<mux_token_secret>”

Now, add your Token Secret and Token ID to this file so that it automatically picks up your credentials. 

Also, if you want to test it, run it on local machine node main.js

The backend of your Flutter App will consist of two main parts, i.e., model classes and Muz client, which are worked on as follows:

  1. Mux Client
  • Create MUXClient class inside a new file.
  • Create Dio Object 

class MUXClient {

  Dio _dio = Dio();

}

  • Add a method

class MUXClient {

  Dio _dio = Dio();

  initializeDio() {

    // initialize the dio here

  }

}

  • Create a file that contains the constants

// API for streaming a video

const muxStreamBaseUrl = ‘https://stream.mux.com’;

// Test video url provided by MUX

const demoVideoUrl = ‘https://storage.googleapis.com/muxdemofiles/mux-video.mp4’;

// API for streaming a video

const muxStreamBaseUrl = ‘https://stream.mux.com’;

  • Storing video to Mux by creating a method and pass video URL to it.

Future<VideoData> storeVideo({String videoUrl}) async {

  Response response;

  try {

    response = await _dio.post(

      “/assets”,

      data: {

        “videoUrl”: videoUrl,

      },

    );

  } catch (e) {

    print(‘Error starting build: $e’);

    throw Exception(‘Failed to store video on MUX’);

  }

  if (response.statusCode == 200) {

    VideoData videoData = VideoData.fromJson(response.data);

    String status = videoData.data.status;

    while (status == ‘preparing’) {

      print(‘processing…’);

      await Future.delayed(Duration(seconds: 1));

      videoData = await checkPostStatus(videoId: videoData.data.id);

      status = videoData.data.status;

    }

    return videoData;

  }

  return null;

  1. Model Class – Two main classes prevail in the model class, which are as follows:
  1. Asset Data 
  2. Video Data 

Both Asset and Video data have further sub-classes, including Track, PlaybackId, and Data. 

  1. Home Page 

This page will contain a TextField, where you can add the URL of the video to upload it to Mux. Add ‘TextField’ and ‘RaisedButton’ for storing the video on Mux. 

  1. Preview Page 

You can preview the page to view the video and show the information related to the file. You can see a video player at the top of the page. Now VideoPlayerControler will be created and stored inside the InitState() of this class. Use Mux stream URL for loading and initializing the video controller. Inside the ‘Column’ create a video player to display the information. 

Finally, the Flutter App is created for streaming videos. 

  1. Testing Video Streaming App 

Once your app is ready, it is time to test it. There are some tests to verify after you have successfully created the app. You can run app tests by using the command:

flutter test

2. HOW TO PLAY AND PAUSE VIDEOS IN FLUTTER APPS 

Flutter Apps

To play videos, the Flutter team provides a video_player plugin, which helps in playing the stored videos on your system (as an asset from the internet). 

Video Player plugin by Flutter for iOS and Android are as follows:

iOS – AVPlayer

Android – ExoPlayer

The plugin offered by Flutter helps in streaming video from the internet with the essential pause and play buttons. Here are the steps that you can follow to add it to your Flutter app. 

  1. Add video_player dependency

Add the dependency to your pubspec.yaml.

dependencies:

  flutter:

    sdk: flutter

  video_player:

  1. Add permissions to the app

Update iOS and Android configurations for adding all necessary permissions to stream the videos from the internet. 

For iOS

<key>NSAppTransportSecurity</key>

<dict>

  <key>NSAllowsArbitraryLoads</key>

  <true/>

</dict>

For Android 

<manifest xmlns:android=”http://schemas.android.com/apk/res/android”>

    <application …>

    </application>

    <uses-permission android:name=”android.permission.INTERNET”/>

</manifest>

  1. Create and initalize a VideoPlayerController

VideoPlayerController allows you to connect different types of video content while controlling the playback. Initialize the controller to create a connection to the video and get the controller ready for playback. 

How to create and initialize the VideoPlayerController? 

Hire Flutter App Developers
  1. Create StatefulWidget with State Class
  2. Add a variable to State class (to store VideoPlayerController)
  3. Add a variable to State class to store the Future received back from VideoPlayerController.initialize
  4. In initState, create and initialize the controller
  5. Use dispose method to dispose the controller 

Here’s the code to do so: 

class VideoPlayerScreen extends StatefulWidget {  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 an 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’,
    );

    _initializeVideoPlayerFuture = _controller.initialize();
 super.initState();
  }

  @override
  void dispose() {
    // Ensure disposing of the VideoPlayerController to free up resources.
    _controller.dispose();
  super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Complete the code in the next step.
    return Container();
  }
}

 
  1. Video Player Displays 

VideoPlayer widget is now available to display the video initialized by VideoPlayerController. Now, wrap the VideoPlayer widget in the AspectRatio widget for setting the appropriate proportions of the video. 

After the _initializeVideoPlayerFuture() is done, you must display the VideoPlayer widget. Now, use FutureBuilder to display the loading spinner. 

// Use a FutureBuilder to display a loading spinner while waiting for the
// VideoPlayerController to finish initializing.
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());
    }
  },
)

  1. Pause and Play the video 

Use the play() and pause() method to play and pause the video. Adding a FloatingActionButton will help you do that. 

Here’s the code to follow:

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,
  ),
)

At last, we really hope that by any chance this unique guide can help you to overcome hurdles to understand the video streaming process. At your Team in India, we have a team of Flutter App Experts. If you want to hire Developers or have any questions on what all services we offer at Your team in India– Click here to contact us

Subscribe to get regular content updates, and offers

Also Read This

Best Offshore Development Team

Cost-Benefit Analysis of Outsourcing

Offshore Development Centre

Offshore Development Center in India

ODC Centre

HOW IT WORKS?