Flutter音频播放插件impulse_player_flutter的使用

Flutter音频播放插件impulse_player_flutter的使用

Impulse Player 使得在 Flutter 中使用视频播放器变得简单。在底层,Impulse Player 使用了 Impulse Player AndroidImpulse Player iOS

此外,Impulse Player 还包含了一些内置功能,如全屏处理。

特性:

  • 单一视图来显示和处理播放器。
  • 可以选择播放质量。
  • 可以选择播放速度。
  • 内置全屏处理。

安装

Flutter

在根目录下的 pubspec.yaml 文件中添加依赖:

dependencies:
  impulse_player: ^0.1.0 # 远程
Android

android/build.gradle 文件中添加仓库:

allprojects {
    repositories {
        // ...
        maven { url "https://jitpack.io" }
    }
}
iOS

ios/Podfile 文件中添加 pod:

pod 'impulse_player_ios'

使用

创建控制器:

final ImpulsePlayerController _controller = ImpulsePlayerController();

使用 ImpulsePlayerView 小部件,并传入创建的控制器:

ImpulsePlayerView(
    controller: _controller,
),
命令

以下是使用播放器的主要命令:

_controller.load(
    "Title",
    "Subtitle",
    "url",
)
_controller.play()
_controller.pause()
_controller.seek(0)
获取器

以下是播放器暴露的值:

_controller.isPlaying() // Boolean, 默认为 `false`
_controller.getState() // PlayerState, 默认为 `Loading`
_controller.getProgress() // Long, 默认为 `0`
_controller.getDuration() // Long, 默认为 `0`
_controller.getError() // String?, 默认为 `null`
代理

监听来自播放器的事件:

final ImpulsePlayerController _controller = ImpulsePlayerController(
onReady: () async {
    print("ImpulsePlayer: onReady");
},
onPlay: () {
    print("ImpulsePlayer: onPlay");
},
onPause: () {
    print("ImpulsePlayer: onPause");
},
onFinish: () {
    print("ImpulsePlayer: onFinish");
},
onError: (message) {
    print("ImpulsePlayer: onError: $message");
},
);

或者,每个回调也可以随时通过控制器直接设置,例如:

_controller.onReady = () async {
   print("ImpulsePlayer: onReady");
   await _controller.load("Title", "Subtitle", "url");
};
自定义

应用自定义外观以定制播放器的外观:

ImpulsePlayer.setAppearance(
    const TextStyle(fontSize: 16, fontFamily: "Inter", fontWeight: FontWeight.w600),
    const TextStyle(fontSize: 14, fontFamily: "Inter", fontWeight: FontWeight.w600),
    const TextStyle(fontSize: 12, fontFamily: "Inter", fontWeight: FontWeight.w400),
    const TextStyle(fontSize: 14, fontFamily: "Inter", fontWeight: FontWeight.w400),
    const TextStyle(fontSize: 10, fontFamily: "Inter", fontWeight: FontWeight.w400),
    const TextStyle(fontSize: 16, fontFamily: "Inter", fontWeight: FontWeight.w400),
    const TextStyle(fontSize: 14, fontFamily: "Inter", fontWeight: FontWeight.w400),
    const Color(0x4945FF),
);

注意:要使用自定义字体,还需要将字体添加到 Android 和 iOS 项目中。否则,自定义字体在 Impulse Player 中将无法工作。

Android:

  • assets 文件夹内,如果不存在 fonts 文件夹,则创建一个。
  • 将字体文件放入该文件夹中,常规字体文件名为 <familyName>.ttf,斜体字体文件名为 <familyName>-<style>.ttf。例如,当使用 Inter 字体时,文件名应为:
    • Inter.ttf
    • Inter-Italic.ttf

iOS:

注意:由于 iOS 中字体的设置方式,从 Flutter 到 iOS 的其他权重(除了常规和粗体)无法使用。因此,权重小于 500 的被确定为 常规,而权重大于等于 500 的被确定为 粗体

  • 将字体文件添加到项目中。
  • Info.plist 中将字体添加到 Fonts provided by application 键下。这些值应该与文件名完全匹配,包括扩展名。

完整示例

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

import 'package:flutter/services.dart';
import 'package:impulse_player_flutter/impulse_player.dart';
import 'package:impulse_player_flutter/impulse_player_controller.dart';
import 'package:impulse_player_flutter/impulse_player_view.dart';
import 'package:impulse_player_flutter/plugin/impulse_player_plugin.dart';
import 'package:impulse_player_flutter/plugin/plugin_platform.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final ImpulsePlayerController _controller = ImpulsePlayerController(
    onReady: () async {
      print("onReady");
    },
    onPlay: () {
      print("onPlay");
    },
    onPause: () {
      print("onPause");
    },
    onFinish: () {
      print("onFinish");
    },
    onError: (message) {
      print("onError: $message");
    },
  );
  final ImpulsePlayerPlugin _plugin = ImpulsePlayerPlugin();

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
    _setCustomAppearance();
    _loadVideo();
    // _controller.onReady = () async {
    //   print("onReady");
    //   await _controller.load("Title", "Subtitle", "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8");
    // };
  }

  void _setCustomAppearance() {
    ImpulsePlayer.setAppearance(
      const TextStyle(fontSize: 16, fontFamily: "Inter", fontWeight: FontWeight.w600),
      const TextStyle(fontSize: 14, fontFamily: "Inter", fontWeight: FontWeight.w600),
      const TextStyle(fontSize: 12, fontFamily: "Inter", fontWeight: FontWeight.w400),
      const TextStyle(fontSize: 14, fontFamily: "Inter", fontWeight: FontWeight.w400),
      const TextStyle(fontSize: 10, fontFamily: "Inter", fontWeight: FontWeight.w400),
      const TextStyle(fontSize: 16, fontFamily: "Inter", fontWeight: FontWeight.w400),
      const TextStyle(fontSize: 14, fontFamily: "Inter", fontWeight: FontWeight.w400),
      const Color(0xFF4945FF),
    );
  }

  void _loadVideo() async {
    await Future.delayed(Duration(seconds: 1));
    await _controller.load("Title", "Subtitle", "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8");
  }

  // 平台消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能会失败,所以我们使用 try/catch PlatformException。
    // 我们也处理消息可能返回 null 的情况。
    try {
      platformVersion = await ImpulsePlayerPluginPlatform.instance.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // 如果小部件在异步平台消息飞行时从树中移除,我们想要丢弃回复而不是调用
    // setState 来更新我们的非存在的外观。
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          // child: Text('运行在: $_platformVersion\n'),
          child: ListView(
            children: [
              Text('运行在: $_platformVersion\n'),
              ImpulsePlayerView(
                controller: _controller,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter音频播放插件impulse_player_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter音频播放插件impulse_player_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


impulse_player_flutter 是一个 Flutter 插件,用于播放音频文件。它提供了简单的 API 来加载、播放、暂停、停止和调整音频的播放速度。以下是如何使用 impulse_player_flutter 插件的详细步骤。

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 impulse_player_flutter 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  impulse_player_flutter: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入插件

在你的 Dart 文件中导入 impulse_player_flutter 插件:

import 'package:impulse_player_flutter/impulse_player_flutter.dart';

3. 初始化播放器

创建一个 ImpulsePlayer 实例来管理音频播放:

ImpulsePlayer player = ImpulsePlayer();

4. 加载音频文件

使用 load 方法来加载音频文件。你可以加载本地文件或网络 URL:

await player.load('https://example.com/audio.mp3');

或者加载本地文件:

await player.load('assets/audio.mp3');

5. 播放音频

使用 play 方法来播放音频:

await player.play();

6. 暂停音频

使用 pause 方法来暂停音频:

await player.pause();

7. 停止音频

使用 stop 方法来停止音频播放:

await player.stop();

8. 调整音量

使用 setVolume 方法来调整音量(范围是 0.0 到 1.0):

await player.setVolume(0.5);

9. 调整播放速度

使用 setSpeed 方法来调整播放速度(1.0 是正常速度):

await player.setSpeed(1.5);

10. 释放资源

在不需要使用播放器时,调用 dispose 方法来释放资源:

await player.dispose();

11. 监听播放状态

你可以监听播放器的状态变化,例如播放完成或出现错误:

player.onPlayerStateChanged.listen((state) {
  if (state == PlayerState.playing) {
    print('Audio is playing');
  } else if (state == PlayerState.paused) {
    print('Audio is paused');
  } else if (state == PlayerState.stopped) {
    print('Audio is stopped');
  } else if (state == PlayerState.completed) {
    print('Audio playback completed');
  }
});

player.onPlayerError.listen((error) {
  print('Error occurred: $error');
});

12. 完整示例

以下是一个完整的示例,展示了如何使用 impulse_player_flutter 插件来播放音频:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AudioPlayerScreen(),
    );
  }
}

class AudioPlayerScreen extends StatefulWidget {
  [@override](/user/override)
  _AudioPlayerScreenState createState() => _AudioPlayerScreenState();
}

class _AudioPlayerScreenState extends State<AudioPlayerScreen> {
  ImpulsePlayer player = ImpulsePlayer();

  [@override](/user/override)
  void initState() {
    super.initState();
    _loadAudio();
  }

  Future<void> _loadAudio() async {
    await player.load('https://example.com/audio.mp3');
  }

  [@override](/user/override)
  void dispose() {
    player.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Audio Player'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                await player.play();
              },
              child: Text('Play'),
            ),
            ElevatedButton(
              onPressed: () async {
                await player.pause();
              },
              child: Text('Pause'),
            ),
            ElevatedButton(
              onPressed: () async {
                await player.stop();
              },
              child: Text('Stop'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部