我需要在不中断现有播放列表的情况下播放音频。我的目标是通过手机上当前的音频服务播放音频,理想情况下,我想避开音频并通过它播放我的流。很像开车时的GPS服务(Waze,谷歌地图)。
步骤:
- 安装依赖项
- 创建initAudioService()函数
- 创建AudioSession实例
- 按照示例配置AudioSession实例
- 按照示例初始化AudioService
- 在运行App之前从main调用initAudioService()
依赖项:
- 音频服务:^0.18.0
- 音频会话:^0.1.6+1
示例:
import‘package:audio_service/audio_service.dart’;import'package:audio_session/audio_session.dart';导入'audio_player_service.dart';Future initAudioService()异步{//audio_session INSTANCEfinal session=等待AudioSession.instance;//音频会话DUCK其他配置等待会话.config(const AudioSessionConfiguration(avAudioSession类别:avAudioSessionCategory.playback,avAudioSession类别选项:avAudioSessionCategoryOptions.duckOthers,avAudioSessionMode:avAudioSessionMode.defaultMode,avAudioSessionRouteSharingPolicy:AVAudioSessionRouteSharingPolicy.defaultPolicy,avAudioSessionSetActiveOptions:avAudioSessionSetActiveOptions.none,androidAudioAttributes:androidAudioAttributes(contentType:AndroidAudioContentType.music,标志:AndroidAudioFlags.none,用法:AndroidAudioUsage.media,),androidAudioFocusGainType:AindAudioFocus GainType.gainTransientMayDuck,androidWillPauseWhenDucked:真的,));//初始化音频服务(_S)return await AudioService.init(builder:()=>AudioPlayerService(),config:cconst AudioServiceConfig(androidNotificationChannelId:'com.YOUR_COMPANY.YOUR_APP_NAME.audio',androidNotificationChannelName:"音频服务演示",androidNotification正在进行:true,androidStopForegroundOnPause:true,),);}//主要void main()异步{等待initAudioService();runApp(const MaterialApp(home:MyApp()));}