Chuyển đến nội dung

Bài 50 · Platform integration

Playing Video and Audio

Play video with video_player and Chewie, play sounds and music with audioplayers, handle controller lifecycle, platform setup, and build a progress bar from player state.

Media is where Flutter's plugin model shows up again: the Dart side is a small API, and the decoding is done by the platform (ExoPlayer on Android, AVFoundation on iOS and macOS, the browser on the web). In this lesson you will use video_player (the official package) and chewie (ready-made controls on top of it) for video, and audioplayers for sound effects and music.

Real vs stand-in. The Dart, manifest and plist snippets are real and read-only, because the site cannot decode media in a Flutter app. The live examples are JavaScript stand-ins of the part you actually write: a player's state machine and the position and progress math. Package APIs change between versions, so check pub.dev before copying code.

Playing video with video_player

A VideoPlayerController is created from a source, initialized (asynchronous: it opens the file or stream and reads its size and duration), shown with the VideoPlayer widget, and disposed.

DART
class VideoScreen extends StatefulWidget {
  const VideoScreen({super.key});
  @override
  State<VideoScreen> createState() => _VideoScreenState();
}

class _VideoScreenState extends State<VideoScreen> {
  late final VideoPlayerController _controller;
  late final Future<void> _ready;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.networkUrl(Uri.parse('https://example.com/clip.mp4'));
    // Other constructors: .asset('assets/clip.mp4'), .file(File(path)), .contentUri(...)
    _ready = _controller.initialize().then((_) => _controller.setLooping(true));
  }

  @override
  void dispose() {
    _controller.dispose();   // frees the native decoder
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<void>(
      future: _ready,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return const Center(child: CircularProgressIndicator());
        }
        return Column(
          children: [
            AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: VideoPlayer(_controller),
            ),
            VideoProgressIndicator(_controller, allowScrubbing: true),
            IconButton(
              icon: ValueListenableBuilder<VideoPlayerValue>(
                valueListenable: _controller,
                builder: (_, value, __) => Icon(value.isPlaying ? Icons.pause : Icons.play_arrow),
              ),
              onPressed: () => _controller.value.isPlaying ? _controller.pause() : _controller.play(),
            ),
          ],
        );
      },
    );
  }
}

Three things to notice. The controller is a ValueNotifier<VideoPlayerValue>, so ValueListenableBuilder rebuilds just the button when playback changes. AspectRatio gives the video its natural shape (see constraints). And dispose is mandatory: a leaked controller keeps a hardware decoder busy. Control methods include seekTo(Duration), setVolume(0..1) and setPlaybackSpeed(double). The value carries position, duration, buffered, isBuffering, isCompleted and hasError.

Stand-in: a player's state machine

JS Position, seek, loop and completion

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Chewie: controls in one widget

video_player draws pixels only. To get a play button, seek bar, full screen and speed menu, wrap the controller in chewie:

DART
final chewie = ChewieController(
  videoPlayerController: _controller,
  autoPlay: true,
  looping: false,
  aspectRatio: 16 / 9,
  allowFullScreen: true,
  allowPlaybackSpeedChanging: true,
);

// in build:
Chewie(controller: chewie)

// in dispose, before the video controller:
chewie.dispose();

Dispose the ChewieController too. Chewie is a good default for tutorials and lists of clips; if your brand needs its own controls, use video_player directly as above.

Playing sound with audioplayers

Short effects and music tracks fit audioplayers. One AudioPlayer plays one source at a time, so make a player per concurrent sound.

DART
final player = AudioPlayer();

Future<void> playChime() async {
  await player.play(AssetSource('audio/chime.mp3'));   // assets/audio/chime.mp3
}

Future<void> playRadio() => player.play(UrlSource('https://example.com/stream.mp3'));

// Controls and state
await player.pause();
await player.resume();
await player.seek(const Duration(seconds: 30));
await player.setVolume(0.6);
await player.setReleaseMode(ReleaseMode.loop);       // repeat

player.onPlayerStateChanged.listen((s) => debugPrint('state: $s'));   // playing, paused, completed...
player.onPositionChanged.listen((pos) => setState(() => _position = pos));
player.onDurationChanged.listen((d) => setState(() => _duration = d));

// when finished with it:
await player.dispose();

AssetSource paths are relative to the assets/ folder you declared in pubspec.yaml (assets). The state and position are streams, consumed like any other (StreamBuilder). For a media app with a lock-screen player, background playback and playlists, look at just_audio with audio_service, and configure the audio session (audio_session) so your app pauses when a call comes in.

JS A progress bar from position and duration streams

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Platform setup

  • Android: playing a network URL needs <uses-permission android:name="android.permission.INTERNET" /> in the main manifest (the debug one has it by default, release builds do not). Cleartext http:// URLs are blocked unless you opt in.
  • iOS: http:// (not https://) sources need an App Transport Security exception in Info.plist; prefer HTTPS.
  • Web: browsers block autoplay with sound until the user interacts. Start playback from a tap. Cross-origin video needs CORS headers.
  • Formats: support depends on the platform's decoder; H.264 MP4 and AAC/MP3 are the safe choices. Streaming HLS (.m3u8) works on mobile; check desktop and web support.

Common mistakes

  • Not disposing the controller or player. Memory and decoder leaks.
  • Building VideoPlayer before initialize() completes. aspectRatio is 1.0 or an error appears; wait for the future.
  • Autoplaying with sound. Many platforms block it and users dislike it.
  • Large videos in the asset bundle. The app grows; stream or download instead (HTTP).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why must you call dispose on a VideoPlayerController?

    The controller owns platform resources that are not released by garbage collection alone.
  2. 2. What does Chewie add on top of video_player?

    video_player renders frames; Chewie wraps it with a control UI.
  3. 3. With audioplayers, how do you play a bundled file assets/audio/chime.mp3?

    AssetSource paths are relative to the assets folder, so the prefix assets/ is left out.
  4. 4. A network video plays in debug but not in a release build on Android. What is a likely cause?

    The debug manifest adds INTERNET automatically, so a missing entry only shows up in release.

Summary

  • VideoPlayerController must be created, initialized, shown with VideoPlayer and disposed; its value notifier drives the UI.
  • chewie adds ready-made controls; audioplayers plays sources and exposes state and position streams.
  • Guard progress math against a zero duration and clamp seeks.
  • Set INTERNET, HTTPS and web-gesture requirements, and prefer streaming for large media.

Next: Launching URLs, Email, SMS and Phone Calls

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.