音频播放器在后台播放,应该与硬件静音开关一起使用

Gan*_*... 8 audio mute audio-player ios avaudiosession

我想在前台,后台播放音频文件,它应该与静音开关一起工作,即如果静音开关打开则不能播放,如果静音开关关闭则应播放音频.

**基本上我正在开发SIP呼叫应用程序.当用户接到电话时,应该播放声音/铃声.它应该在app处于后台/前台时播放,如果硬件静音开关为ON/OFF,它应该静音/取消静音.

为此,我使用了AVPlyaer以下代码.

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
[session setActive:YES error:nil];

NSURL * audioFileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test1" ofType:@"mp3"]];
AVPlayer *player = [[AVPlayer alloc] initWithURL: audioFileUrl];
[player play];
Run Code Online (Sandbox Code Playgroud)

此外,我还在info.plist中添加了"App播放音频或使用AirPlay传输音频/视频"到后台模式

这是在两种模式下播放,但在硬件静音开关打开时不静音.如果我使用"AVAudioSessionCategoryAmbient"不在后台模式上播放.我使用AVAudioPlayer但在硬件开关打开时无法找到静音

请帮我修复它或任何其他方法来实现这一目标.提前致谢.

Gan*_*... 2

很高兴地说,我发现了 Skype 是如何实现此功能的。

在前台,我们可以使用 AVAudioSession 与任何一种类别来播放铃声。

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory: AVAudioSessionCategorySoloAmbient error:&error];
[session setActive:YES error:nil];

NSURL * audioFileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test1" ofType:@"mp3"]];
AVPlayer *player = [[AVPlayer alloc] initWithURL: audioFileUrl];
[player play];
Run Code Online (Sandbox Code Playgroud)

在后台,我们必须使用带有自定义声音的本地通知。这将与硬件静音开关配合使用。但这里声音文件长度不应超过30秒。

    UILocalNotification* notification = [[UILocalNotification alloc] init];
    [notification @"Title"];
    [notification setAlertBody:@"Body"];
    [notification setAlertAction:noteAction];
    [notification setSoundName:@"ringtone.mp3"];
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
Run Code Online (Sandbox Code Playgroud)

希望这会有用:)。