我有一个需要播放声音的锻炼应用程序。我使用AVAudioPlayer来播放声音。但当音频开始播放时,另一个应用程序(广播流媒体应用程序)的背景音乐就会关闭。
我怎样才能使它不打断背景音乐?因为我希望用户在锻炼时能听到音乐。
谢谢。
您可以在使用AVAudioPlayer时使用以下代码:
// Set AudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
如果你想设置一个代理人,你可以添加这行代码:
[[AVAudioSession sharedInstance] setDelegate:self];
在我的情况下,我希望以较低的音量播放背景音频,因为我的应用程序播放的声音更像是一个警报。我使用这个:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// prevents our app from stopping other audio,
// e.g. music, podcats, etc. that may be playing when launched
// our audio will be played at a higher volume
// and the background audio will "duck" until done
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryMultiRoute
withOptions:AVAudioSessionCategoryOptionDuckOthers
error:nil];
}
根据SujithPt的回答,swift中的内容相同:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
对于Swift 4.2
import AVFoundation
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default, options: AVAudioSession.CategoryOptions.mixWithOthers)
} catch let error {
print(error.localizedDescription)
}
return true
}
对于Swift 2.2,请在播放或准备播放之前将其添加到任何位置:
_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)