我正在使用 Xamarin,所以这是 C#,但以下代码对我有用。我首先设置我的 AppDelegate 通过包含 IAVAudioSessionDelegate 来实现 AVAudioSession 委托方法
public partial class AppDelegate: UIApplicationDelegate, IAVAudioSessionDelegate
我为音频会话的 AppDelegate 类添加了一个变量
public static AVAudioSession AudioSession;
在 FinishedLaunching 方法的覆盖中:
AudioSession = AVAudioSession.SharedInstance();
AudioSession.Delegate = this;
error = AudioSession.SetCategory( AVAudioSessionCategory.Playback, AVAudioSessionCategoryOptions.DuckOthers );
AudioSession.SetMode( new NSString( "AVAudioSessionModeMoviePlayback" ), out error );
AppDelegate.cs 中两个相关的委托方法是:
[Export( "beginInterruption" )]
public void BeginInterruption()
{
PlayerViewController.BeginSessionInterruption();
}
[Export( "endInterruptionWithFlags:" )]
public void EndInterruption( AVAudioSessionInterruptionFlags flags )
{ // ignore the flags so we're not dependent on the interrupting event saying that we can resume
PlayerViewController.ResumeAfterSessionInterruption();
}
我的 AppDelegate 还具有对 OnActivated 的覆盖以启用视频轨道(如果它是视频资产),以及对 DidEnterBackground 的覆盖以禁用媒体的视频轨道但仍播放音频。
在 PlayerViewController.BeginSessionInterruption() 方法中,我无法查看 Player.Rate 来查看播放器当时是否正在运行,因为中断的警报或电话已经暂停播放器。来自 Apple 音频会话编程指南的“响应中断”部分,我的重点是:
- 您的应用处于活动状态,正在播放音频。
- 来了一个电话。系统会激活手机应用的音频会话。
- 系统会停用您的音频会话。此时,* 在您的应用中播放已停止 *。
- 系统调用您的中断监听回调函数,表明您的会话已被停用。
...
我的 PlayerViewController 的播放按钮有一个 Paused 属性,用于在播放和暂停之间切换并绘制适当的按钮图像。因此,我没有检查 Player.Rate,而是查看按钮的 Paused 属性是否为 false:
public void BeginSessionInterruption()
{
PlayerWasRunningOnInterruption = !btnPlay.Paused;
TogglePlayPause( true ); // put the Play button into the Paused state to agree with the player being stopped
public void ResumeAfterSessionInterruption()
{
NSError error;
AppDelegate.AudioSession.SetActive( true, AVAudioSessionSetActiveOptions.NotifyOthersOnDeactivation, out error ); // always reactivate the audio session
if ( PlayerWasRunningOnInterruption )
{
// rewind a little bit
// call btnPlayClick to resume the playback as if the user pressed the Play button
}
}