我有一个需要播放声音的锻炼应用程序。我使用 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 的回答,这里是同样的事情:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
对于斯威夫特 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)