音频播放器在后台播放,应该与硬件静音开关一起使用 [英] Audio Player play in background and should be work with hardware mute switch

查看:177
本文介绍了音频播放器在后台播放,应该与硬件静音开关一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在前台,后台播放音频文件,它应该使用静音开关,即如果静音开关打开则不能播放,如果静音开关关闭则应播放音频。

I want to play audio file in the foreground,background and it should work with mute switch i.e. if mute switch is on should not play, if mute switch is off should play audio.

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

**Basically am developing SIP call application. App should play sound/ringtone when user receives a call. It should play if app is in background/foreground, it should mute/unmute if hardware mute switch is ON/OFF.

为此,我使用AVPlyaer和下面的代码。

For this I used AVPlyaer with below code.

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];

我还添加了App播放音频或使用AirPlay传输音频/视频到背景模式的信息.plist

And also I added "App plays audio or streams audio/video using AirPlay" to background modes in info.plist

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

This is playing in both modes but not mute when hardware mute switch is ON. If I use "AVAudioSessionCategoryAmbient" not playing on the background mode. I used AVAudioPlayer but not able to find mute when hardware switch is ON

请帮我修复它或以任何其他方式实现此目的。
先谢谢。

Please help me to fix it or any other way to achieve this. Thanks in Advance.

推荐答案

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

Am happy to say, I found how skype is achieving this feature.

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

In foreground we can use AVAudioSession with any one category to play ringtone.

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];

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

In background we have to use local notification with custom sound. This will work with hardware mute switch. But here sound file length should not exceed 30 seconds.

    UILocalNotification* notification = [[UILocalNotification alloc] init];
    [notification @"Title"];
    [notification setAlertBody:@"Body"];
    [notification setAlertAction:noteAction];
    [notification setSoundName:@"ringtone.mp3"];
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

希望这会有用:)。

这篇关于音频播放器在后台播放,应该与硬件静音开关一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆