如何在Flutter的所有平台(包括Web)上播放音频

时间:2019-12-27 10:28:43

标签: flutter audio flutter-web

current audio plugins不支持网络。假设我有本地音频文件或远程URL,如何在所有平台上播放?

我找到了使用video_player的解决方案,因此,我在下面与大家分享此问题,作为自我解答。

1 个答案:

答案 0 :(得分:3)

Flutter的video_player插件还支持音频,因此您可以使用它。它目前支持Android,iOS和Web,并且可能会在其他平台变得稳定后支持它们。

这里是Video Player cookbook example,适合播放音频文件。我用mp3链接替换了mp4链接,并删除了视频所需的AspectRatio小部件。 (不要忘记将video_player依赖项添加到 pubspec.yaml 。)

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() => runApp(VideoPlayerApp());

class VideoPlayerApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Player Demo',
      home: VideoPlayerScreen(),
    );
  }
}

class VideoPlayerScreen extends StatefulWidget {
  VideoPlayerScreen({Key key}) : super(key: key);

  @override
  _VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  VideoPlayerController _controller;
  Future<void> _initializeVideoPlayerFuture;

  @override
  void initState() {

    // Using an mp3 file instead of mp4.
    _controller = VideoPlayerController.network(
      'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3',
    );

    _initializeVideoPlayerFuture = _controller.initialize();

    _controller.setLooping(true);

    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Butterfly Video'),
      ),
      body: FutureBuilder(
        future: _initializeVideoPlayerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            // not wrapped in an AspectRatio widget
            return 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,
        ),
      ),
    );
  }
}

要支持网络,您还需要添加video_player_web依赖项。

dependencies:
  video_player: ^0.10.4
  video_player_web:
    git:
      url: git://github.com/flutter/plugins.git
      path: packages/video_player/video_player_web

请注意,将来不会使用git。请参阅说明here

更新:实际上,它无需指定video_player_web即可在网络上运行。