简体   繁体   中英

AVAudioSession doesn't respect mixWithOthers

I'm trying to build an alarm app. To play alarms when the app is in the background, my app plays a completely silence sound (however I'm hearing a quiet noise, although if I play the same sound file on my computer there is definitely nothing to hear) in the background until the alarm time comes and the AVPlayer plays the alarm sound. It works, but when my app plays the silent sound in the background, some other apps (especially some games) don't play their sound. This is kind of weird, because there is the app 'Alarmy' in the AppStore, which definitely uses the same system with a silent sound, but when I set an alarm in this app, it doesn't silence any other sound.

How can I achieve this? Currently I'm setting my AVAudioSession like this (I'm setting it in the initializer of my alarm player class, of which i have an instance in my AppDelegate):

let session = AVAudioSession.sharedInstance()
do {
    try session.setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
    try session.setActive(true)
} catch {
    print("Failed to set audio session category.  Error: \(error)")
}

EDIT: For more explanation about the app Alarmy, look also at App "Alarmy" is able to play iTunes song from background state... How?

"To play alarms when the app is in the background, my app plays a completely silence sound." Do you mean you're trying to use playing silence to keep your app alive? This isn't allowed. If you've found other apps that do this (how do you know they're doing it that way?), that doesn't mean it's allowed. The fact that someone has gotten away with something doesn't change AppStore rules (and doesn't change the fact that silent audio is a major battery drain).

The correct way to build an app that launches at a specific time to play an alarm is with a UNNotificationRequest . You can register the notification to wake you up at a given date and time and you can perform your alarm then, or (often better) just have the notification take care of the alarm without waking you up until the user taps on the message.

See the Local and Remote Notification Programming Guide for full details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM