flutter 音频层”和“audio_service”的播放被其他媒体应用程序中断

yh2wf1be  于 2023-01-14  发布在  Flutter
关注(0)|答案(1)|浏览(346)

我用的是audiolayersaudio_service播放音频,效果很好,当我打开其他音频应用(比如Apple Music)播放音乐时,我的应用会停止播放,这还可以,但当我返回应用查询当前播放状态时,它还在播放。
这是我的代码:

Container(
    height: 60.w,
    width: 60.w,
    decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(30.w),
        gradient: const LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [Color(0xFFD54381), Color(0xFF7644AD)]),
        ),
        child: StreamBuilder<PlaybackState>(
           stream: customAudioHandler?.playbackState,
           builder: (context, snapshot) {
             final playing = snapshot.data?.playing ?? false;
             return GestureDetector(
                onTap: () => _playOrPause(context, playing),
                  child: Icon(
                    playing ? FontIcons.stop : FontIcons.play,
                    color: Colors.white,
                    size: 40.w,
                 ),
              );
           },
        ),
   ),

我尝试使用WidgetsBindingObserver
例如:

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.paused:
        break;
      case AppLifecycleState.resumed:
        var audioHandlerState = customAudioHandler?.playbackState.value.playing;
        var audioPlayerState = audioPlayer.state;

        // print true
        debugPrint('didChangeAppLifecycleState-resumed: $audioHandlerState'); 

        // print PlayerState.playing
        debugPrint('didChangeAppLifecycleState-resumed: $audioPlayerState'); 

        break;
      case AppLifecycleState.detached:
        break;
    }
    super.didChangeAppLifecycleState(state);
  }

其输出状态为播放
任何帮助都将不胜感激。

c86crjj0

c86crjj01#

当您的应用的音频会话被另一个应用的音频会话中断时,您可能希望以某种方式收到通知,以便您可以更新应用的状态(在您的情况下,使用playing=false广播新的playbackState)。
您可以通过Flutter audio_session软件包访问音频会话。通过会话示例,您可以在会话被其他应用中断时收听:

session.interruptionEventStream.listen((event) {
  if (event.begin) {
    switch (event.type) {
      case AudioInterruptionType.duck:
        // Here you could lower the volume
        break;
      case AudioInterruptionType.pause:
      case AudioInterruptionType.unknown:
        // Here you should pause your audio
        player.pause();
        // AND ALSO broadcast the new state
        playbackState.add(playbackState.value.copyWith(playing: false));
        break;
    }
  }
});

官方的audio_service示例也演示了这个用例,尽管使用了不同的音频播放器插件(just_audio),它使用audio_session使这个用例更容易。

相关问题