1. 插件介绍
Flutter Audio Session 是一个强大的 Flutter 插件,用于管理应用程序的音频会话。它能够告诉操作系统应用程序的音频性质(如音乐播放器、语音助手等),并处理音频中断(如电话来电)。该插件提供了对 iOS 的 AVAudioSession 和 Android 的 AudioManager 的完整访问能力,同时也支持鸿蒙系统。
主要功能包括:
- 配置音频会话类型(音乐、语音等)
- 处理音频中断(暂停、降低音量等)
- 监听耳机插拔事件
- 检测音频设备变化
- 控制音频焦点
2. 插件安装
由于这是一个自定义修改版本的三方库,需要通过 Git 形式引入。在项目的 pubspec.yaml 文件中添加以下依赖配置:
dependencies:
audio_session:
git:
url: "https://gitcode.com/openharmony-sig/flutter_audio_session.git"
配置完成后,执行以下命令获取依赖:
flutter pub get
3. 使用方法
3.1 基本使用
首先,需要初始化音频会话并进行配置。以下是配置为音乐播放的示例:
import 'package:audio_session/audio_session.dart';
// 获取音频会话实例
final session = await AudioSession.instance;
// 配置为音乐播放类型
await session.configure(AudioSessionConfiguration.music());
如果是播放播客或有声书,可以使用语音配置:
await session.configure(AudioSessionConfiguration.speech());
3.2 自定义配置
您也可以根据需要进行自定义配置:
await session.configure(AudioSessionConfiguration(
avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
avAudioSessionCategoryOptions: AVAudioSessionCategoryOptions.allowBluetooth,
avAudioSessionMode: AVAudioSessionMode.spokenAudio,
avAudioSessionRouteSharingPolicy: AVAudioSessionRouteSharingPolicy.defaultPolicy,
avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
androidAudioAttributes: const AndroidAudioAttributes(
contentType: AndroidAudioContentType.speech,
flags: AndroidAudioFlags.none,
usage: AndroidAudioUsage.voiceCommunication,
),
androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
androidWillPauseWhenDucked: true,
));
3.3 激活音频会话
在播放音频前,需要激活音频会话:
// 激活音频会话
if (await session.setActive(true)) {
// 现在可以播放音频了
} else {
// 请求被拒绝,应用不应播放音频(例如有电话正在进行)
}
3.4 处理音频中断
当有其他应用需要音频焦点时(如电话来电、导航提示等),可以监听音频中断事件并做出相应处理:
session.interruptionEventStream.listen((event) {
if (event.begin) {
switch (event.type) {
case AudioInterruptionType.duck:
// 其他应用开始播放音频,应该降低音量
break;
case AudioInterruptionType.pause:
case AudioInterruptionType.unknown:
// 其他应用开始播放音频,应该暂停
break;
}
} else {
switch (event.type) {
case AudioInterruptionType.duck:
// 中断结束,应该恢复音量
break;
case AudioInterruptionType.pause:
// 中断结束,可以恢复播放
case AudioInterruptionType.unknown:
// 中断结束,但不应该自动恢复
break;
}
}
});
3.5 监听耳机事件
当用户拔下耳机时,可以监听事件并暂停播放:
session.becomingNoisyEventStream.listen((_) {
// 用户拔下了耳机,应该暂停播放
player.pause();
});
3.6 监听设备变化
可以监听音频设备的添加和移除:
session.devicesChangedEventStream.listen((event) {
print('添加的设备: ${event.devicesAdded}');
print('移除的设备: ${event.devicesRemoved}');
});
4. 完整示例
以下是一个在鸿蒙系统上使用 Flutter Audio Session 播放音频的完整示例:
import 'package:audio_session/audio_session.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final player = AudioPlayer();
final String url = "https://luan.xyz/files/audio/ambient_c_motion.mp3";
PlayerState playerState = PlayerState.stopped;
void initState() {
super.initState();
AudioSession.instance.then((audioSession) async {
// 配置音频会话为语音类型
await audioSession.configure(AudioSessionConfiguration.speech());
// 处理音频中断
_handleInterruptions(audioSession);
});
}
void _handleInterruptions(AudioSession audioSession) {
bool playInterrupted = false;
// 监听耳机插拔事件
audioSession.becomingNoisyEventStream.listen((_) {
print('检测到耳机插拔,暂停播放');
player.pause();
});
// 监听播放器状态变化
player.onPlayerStateChanged.listen((event) {
print('播放器状态变化: $event');
playInterrupted = false;
if (event == PlayerState.playing) {
audioSession.setActive(true);
}
setState(() {
this.playerState = event;
});
});
// 监听音频中断事件
audioSession.interruptionEventStream.listen((event) {
print('音频中断开始: ${event.begin}');
print('音频中断类型: ${event.type}');
if (event.begin) {
switch (event.type) {
case AudioInterruptionType.duck:
// 降低音量
playInterrupted = false;
break;
case AudioInterruptionType.pause:
case AudioInterruptionType.unknown:
// 暂停播放
if (this.playerState == PlayerState.playing) {
player.pause();
playInterrupted = true;
}
break;
}
} else {
switch (event.type) {
case AudioInterruptionType.duck:
// 恢复音量
playInterrupted = false;
break;
case AudioInterruptionType.pause:
// 恢复播放
if (playInterrupted) player.play(UrlSource(url));
playInterrupted = false;
break;
case AudioInterruptionType.unknown:
playInterrupted = false;
break;
}
}
});
}
Future<void> play() async {
await player.stop();
await player.play(UrlSource(url));
}
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('音频会话示例'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(
playerState == PlayerState.playing ? Icons.pause : Icons.play_arrow,
),
iconSize: 64.0,
onPressed: playerState == PlayerState.playing ? player.pause : play,
),
SizedBox(height: 20),
Text(
playerState == PlayerState.playing ? '播放中' : '已暂停',
style: TextStyle(fontSize: 18),
),
],
),
),
),
);
}
}
5. 注意事项
-
兼容性:
- Flutter: 3.7.12-ohos-1.0.6 或 3.22.1-ohos-1.0.1
- SDK: 5.0.0(12)
- IDE: DevEco Studio 5.0.13.200
-
音频焦点:
- 通常情况下,播放音频的插件会自动激活音频会话
- 如果需要手动控制,可以使用
session.setActive(true/false)
-
设备权限:
- 如果应用使用麦克风,需要在相应平台添加麦克风权限
6. 总结
Flutter Audio Session 插件为鸿蒙系统上的音频应用开发提供了强大的支持,能够帮助开发者轻松管理音频会话、处理音频中断和设备变化等。通过合理配置和使用该插件,可以提升音频应用的用户体验,确保应用在各种场景下都能正确处理音频。
欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.youkuaiyun.com
1518

被折叠的 条评论
为什么被折叠?



