简体   繁体   中英

Mute My App When Other Apps are Playing Music in Swift

I'm writing an app that plays music. However, I'd like to make it so that my app's music pauses when other music is playing, such as music from iTunes. How would I accomplish this? Here's my code:

 var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ambler", ofType: "mp3")!)

    // Removed deprecated use of AVAudioSessionDelegate protocol
    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)

    var error:NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
    audioPlayer.prepareToPlay()
    audioPlayer.play()
    audioPlayer.numberOfLoops = -1

To do this I believe you are going to need to check if the music player is playing, here is how I would do that in Objective-C.

First #import <MediaPlayer/MediaPlayer.h> and add the library to your build phases.

- (BOOL)isPlaying
{
    MPMusicPlayerController *musicPlayer = [MPMusicPlayerController systemMusicPlayer];
    if (musicPlayer.playbackState == MPMusicPlaybackStatePlaying) {
        return YES;
    }
    return NO;
}

When initializing musicPlayer it may cause the music to stop, if so I would look into

+ (MPMusicPlayerController *)applicationMusicPlayer

Swift

func isPlaying() -> Bool {

    let musicPlayer = MPMusicPlayerController.systemMusicPlayer()
    if musicPlayer.playbackState == MPMusicPlaybackState.Playing {
        return true
    }
    return false
}

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