iOS: How do I detect if music is playing in any background music app?

后端 未结 4 735
南笙
南笙 2020-12-15 21:32

I currently have my game correctly handling disabling its own BGM when music is playing in the built-in iPod app, but it does not detect when an app such as Pandora is playi

相关标签:
4条回答
  • 2020-12-15 21:56

    Check out this question

    Seems you can see if another audio is playing by checking the property kAudioSessionProperty_OtherAudioIsPlaying like this:

    UInt32 propertySize, audioIsAlreadyPlaying=0;
    propertySize = sizeof(UInt32);
    AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &propertySize, &audioIsAlreadyPlaying);
    

    A complement to this could be to ask the user if he/she wants to have the game music or the already playing sound/music.

    0 讨论(0)
  • 2020-12-15 22:02

    AudioSessionGetProperty (as mentioned in jake_hetfield's answer) is deprecated as of iOS 7.

    Instead, try this one-liner that uses isOtherAudioPlaying:

    BOOL isOtherAudioPlaying = [[AVAudioSession sharedInstance] isOtherAudioPlaying];
    

    Works on iOS 6+.

    0 讨论(0)
  • 2020-12-15 22:09

    You may want to do something like this.....

    1. Create A class to handle your audio settings say... "AudioManager"

    2. Poll the Boolean "isOtherAudioPlaying"... maybe assign it to your own Boolean value.

    import Foundation
    import AVFoundation
    
    class AudioManager {
        static let successBingSoundID: SystemSoundID = <Your System Sound ID in Int>
        static func playSystemSoundIfBackgroundSoundIsOff() {
            guard !AVAudioSession.sharedInstance().isOtherAudioPlaying else {return}
            AudioServicesPlaySystemSoundWithCompletion(successBingSoundID, nil)
        }
    }
    

    usage:

    AudioManager.playSystemSoundIfBackgroundSoundIsOff()
    
    0 讨论(0)
  • 2020-12-15 22:11

    As of iOS 8, the secondaryAudioShouldBeSilencedHint property should be used:

    /* Will be true when another application with a non-mixable audio session is playing audio.  Applications may use
    this property as a hint to silence audio that is secondary to the functionality of the application. For example, a game app
    using AVAudioSessionCategoryAmbient may use this property to decide to mute its soundtrack while leaving its sound effects unmuted.
    Note: This property is closely related to AVAudioSessionSilenceSecondaryAudioHintNotification.
    */
    @property(readonly) BOOL secondaryAudioShouldBeSilencedHint  NS_AVAILABLE_IOS(8_0);
    
    0 讨论(0)
提交回复
热议问题