flutter_vlc_player

repository·master·Indexed 20 days ago

https://github.com/solid-software/flutter_vlc_player

A VLC-powered video player plugin for Flutter supporting iOS and Android. It provides an alternative to the standard video_player package with additional features such as Chromecast support, video recording, and advanced VLC configuration options for caching, clock synchronization, and HTTP behavior. The plugin includes VlcPlayerController for media initialization and the VlcPlayer widget for display.

Tokens
8.5K
Snippets
25
Records
33
Agent score
70%

What's inside flutter_vlc_player

  1. Upgrade to Version 5.0

    master

    Upgrading to version 5.0 requires migrating your iOS project to Swift. Follow these steps:

    1. Clean the repository:
      git clean -xdf
    2. Delete the existing ios folder from your Flutter project root (back up any custom changes first).
    3. Re-create the iOS directory with Swift support:
      flutter create -i swift .
    4. Update your Info.plist and Podfile according to any warnings shown by the Flutter tools.
    5. If you had custom changes in your old ios folder, manually copy them into the new directory.

    Note: Version 5.0 includes a complete platform refactor and contains breaking changes from V4.

  2. Configure Android for flutter_vlc_player

    master

    Follow these steps to configure Android permissions and build settings:

    Permissions

    In <project root>/android/app/src/main/AndroidManifest.xml:

    Internet Access (for remote media/subtitles):

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

    Note: This is often included by default in Flutter projects.

    Local Storage (for internal device media/subtitles):

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    Network Security

    If you encounter "Cleartext HTTP traffic to * is not permitted", add android:usesCleartextTraffic="true" to the <application> tag in AndroidManifest.xml.

    To avoid access denied errors on Android 10, add android:requestLegacyExternalStorage="true" to the <application> tag. When using this, access files via paths like /storage/emulated/0/{FilePath} or /sdcard/{FilePath}.

    Build Configuration

    1. In android/app/build.gradle, add packagingOptions to resolve duplicate C++ library issues:
    android {
        packagingOptions {
            pickFirst 'lib/**/libc++_shared.so'
        }
        // ...
    }
    1. Create android/app/proguard-rules.pro and add the following to prevent VLC classes from being stripped during minification:
    -keep class org.videolan.libvlc.** { *; }
  3. Configure iOS for flutter_vlc_player

    master

    To ensure the plugin works correctly on iOS, follow these configuration steps:

    App Transport Security (ATS)

    If you are loading media from external/non-HTTPS sources, add the following to your Info.plist:

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
    </dict>

    Podfile Requirements

    Ensure the following line is uncommented in <project root>/ios/Podfile: platform :ios, '9.0'

    Chromecast/External Display Support

    To enable VLC casting functionality, add these keys to your Info.plist:

    <key>NSLocalNetworkUsageDescription</key>
    <string>Used to search for chromecast devices</string>
    <key>NSBonjourServices</key>
    <array>
      <string>_googlecast._tcp</string>
    </array>

    Note: Unlike the standard Flutter video_player, flutter_vlc_player is fully functional on iOS simulators.

  4. Implement a new platform for the vlc plugin

    master

    To create a new platform-specific implementation for the vlc plugin, you must extend the VlcPlatform class. Once your implementation is written, you must register it as the default platform by assigning it to VlcPlatform.instance during your plugin registration process.

    // 1. Extend VlcPlatform with your implementation
    class MyPlatformVlc extends VlcPlatform {
      // Implement platform-specific behavior here
    }
    
    // 2. Register the implementation
    VlcPlatform.instance = MyPlatformVlc();
  5. Customize iOS launch screen assets

    master

    To change the launch screen image for the iOS version of your app, you can either replace the image files directly in the ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory or use Xcode.

    To use Xcode:

    1. Open your Flutter project's iOS workspace using open ios/Runner.xcworkspace.
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired images into the asset catalog.
    open ios/Runner.xcworkspace
  6. Understand the VlcPlayerValue state model

    master

    The VlcPlayerValue class represents the complete current state of a VlcPlayerController. You can use this object to inspect playback progress, media properties, buffering status, and error states.

    Key properties include:

    • Playback State: playingState, isPlaying, isBuffering, isEnded, and isLooping.
    • Time & Progress: duration (total length), position (current playback point), and playbackSpeed.
    • Media Properties: size (video dimensions), aspectRatio (calculated width/height), audioTracksCount, spuTracksCount (subtitles), and videoTracksCount.
    • Audio/Subtitle Selection: activeAudioTrack, activeSpuTrack, and activeVideoTrack along with their respective delays.
    • Recording: isRecording and recordPath (the path of the recorded file).
    • Error Handling: errorDescription and the hasError getter.

    If the player is not yet initialized, duration and size will be Duration.zero and Size.zero respectively.

  7. Initialize VlcPlayerController

    master

    To use the VlcPlayerController, you must first create an instance using one of the specialized constructors and then call initialize(). The controller manages the playback state and provides updates via a ValueNotifier<VlcPlayerValue>.

    Important Lifecycle Notes:

    • Instances must be initialized with initialize() before calling most playback methods.
    • To reclaim resources used by the player, you must call dispose().
    • After dispose(), all further calls to the controller are ignored.
    // Example: Initializing a network player
    final controller = VlcPlayerController.network(
      'https://example.com/video.m3u8',
      autoInitialize: true,
      autoPlay: true,
    );
    
    // Ensure you dispose it when the widget is removed
    @override
    void dispose() {
      controller.dispose();
      super.dispose();
    }
  8. Quick Start with flutter_vlc_player

    master

    To implement a basic video player, use the VlcPlayerController to initialize the media and the VlcPlayer widget to display it.

    Example of playing a network stream with hardware acceleration enabled:

    import 'package:flutter/material.dart';
    import 'package:flutter_vlc_player/flutter_vlc_player.dart';
    
    // ... (MyApp and MyHomePage boilerplate)
    
    class _MyHomePageState extends State<MyHomePage> {
      VlcPlayerController _videoPlayerController;
    
      @override
      void initState() {
        super.initState();
    
        _videoPlayerController = VlcPlayerController.network(
          'https://media.w3.org/2010/05/sintel/trailer.mp4',
          hwAcc: HwAcc.full,
          autoPlay: false,
          options: VlcPlayerOptions(),
        );
      }
    
      @override
      void dispose() async {
        super.dispose();
        await _videoPlayerController.stopRendererScanning();
        await _videoPlayerController.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("VLC Player"),
          ),
          body: Center(
            child: VlcPlayer(
              controller: _videoPlayerController,
              aspectRatio: 16 / 9,
              placeholder: Center(child: CircularProgressIndicator()),
            ),
          ),
        );
      }
    }
  9. Record video with VlcPlayerController

    master

    You can record the video playback using the following methods on the VlcPlayerController:

    1. Call startRecording(String saveDirectory) to begin the recording process.
    2. Call stopRecording() to end the recording.
    3. After stopping, retrieve the path of the recorded file from vlcPlayerController.value.recordPath.

    Known Issue: On iOS and Android, if the video reaches its end while recording, the underlying vlckit/libvlc library may fail to finalize the recording, making the file unretrievable.

  10. Listen to initialization and renderer events

    master

    Instead of using deprecated constructor parameters, use the following listener methods to react to player lifecycle and hardware events:

    Initialization Listener

    Register a callback to be executed once the platform view has been initialized:

    • addOnInitListener(VoidCallback listener)
    • removeOnInitListener(VoidCallback listener)

    Renderer (Cast) Listener

    Register a callback to be executed when a cast renderer device (like Chromecast) is attached or detached. The callback signature is void Function(VlcRendererEventType, String, String) where the arguments are (type, uniqueId, name):

    • addOnRendererEventListener(RendererCallback listener)
    • removeOnRendererEventListener(RendererCallback listener)
    controller.addOnInitListener(() {
      print('Player is ready!');
    });
    
    controller.addOnRendererEventListener((type, id, name) {
      print('Renderer $name ($id) is now $type');
    });
  11. Use the VlcPlayer widget

    master

    The VlcPlayer widget is the primary UI component used to render video content. It requires a VlcPlayerController to manage the playback state and an aspectRatio to define the video's dimensions.

    Parameters

    • controller: The VlcPlayerController instance responsible for the video being rendered.
    • aspectRatio: The aspect ratio used to display the video. This is mandatory. A common way to calculate this is parentWidth / parentHeight (e.g., using a LayoutBuilder).
    • placeholder: An optional widget (such as a CircularProgressIndicator) to display while the platform view is initializing.
    • virtualDisplay: A boolean determining whether Virtual displays or Hybrid composition is used on Android. Note that iOS only uses Hybrid composition. Defaults to true.
    VlcPlayer(
      controller: myVlcPlayerController,
      aspectRatio: 16 / 9,
      placeholder: CircularProgressIndicator(),
      virtualDisplay: true,
    );