audio播放器在后台播放,应使用硬件静音开关
我想在前台,后台播放audio文件,并且应该使用静音开关,即静音开关打开时不应该播放,如果静音开关closures,应该播放audio。
**基本上正在开发SIP通话应用程序。 应用程序应该在用户接听电话时播放声音/铃声。 如果应用程序在后台/前台应该播放,如果硬件静音开关打开/closures,它应该静音/取消静音。
为此我用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];
另外,我还在info.plist中添加了“应用程序播放audio或使用AirPlay播放audio/video”的背景模式
硬件静音开关打开时,这两种模式都是播放,但不是静音。 如果我使用“AVAudioSessionCategoryAmbient”不在背景模式下播放。 我使用AVAudioPlayer,但硬开关打开时无法find静音
请帮我解决它或任何其他方式来实现这一点。 提前致谢。
您的audio会话类别可能设置不正确。 既然你要尊重静音开关,你应该使用SoloAmbient
AVAudioSessionCategorySoloAmbient
默认类别的类别,除非您使用setCategory:error:或setCategory:withOptions:error:方法设置类别。
您的audio通过屏幕locking和静音开关(iPhone上的Ring / Silent开关)静音。
默认情况下,使用此类别意味着您的应用程序的audio是不可混合的 – 激活您的会话将中断任何其他audio会话也是不可混合的。 要允许混合,请改用AVAudioSessionCategoryAmbient类别。
在iOS 3.0及更高版本中可用。
您似乎已经使用这个类别:
AVAudioSessionCategoryPlayback
用于播放录制音乐或其他声音的类别,这些对于成功使用您的应用程序至关重要。
使用此类别时, 应用程序audio会继续,无声开关设置为静音或屏幕locking。 (此开关称为iPhone上的铃声/静音开关。)要在应用程序转换到背景时继续播放audio(例如,屏幕locking时),请将audio值添加到信息属性列表文件中的UIBackgroundModes项。
默认情况下,使用此类别意味着您的应用程序的audio是不可混合的 – 激活您的会话将中断任何其他audio会话也是不可混合的。 要允许为此类别混音,请使用AVAudioSessionCategoryOptionMixWithOthers选项。
在iOS 3.0及更高版本中可用。
资料来源: https : //developer.apple.com/library/prerelease/ios/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/index.html#//apple_ref/doc/constant_group/Audio_Session_Categories
我很高兴地说,我发现Skype是如何实现这一function。
在前台,我们可以使用任何一个类别的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];
在后台我们必须使用自定义声音的本地通知。 这将与硬件静音开关一起工作。 但是这里声音文件的长度不应该超过30秒。
UILocalNotification* notification = [[UILocalNotification alloc] init]; [notification @"Title"]; [notification setAlertBody:@"Body"]; [notification setAlertAction:noteAction]; [notification setSoundName:@"ringtone.mp3"]; [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
希望这将是有益的:)。
以下是一个用于检测静音开关状态的库: http : //sharkfood.com/content/Developers/content/Sound%20Switch/ 。 它基于苹果的公共API。 它只是播放系统声音和测量完成播放所用的时间量。 它在Instagram iOS应用程序中使用。