How can I allow background music to continue playing while my app still plays its sounds while using Swift

后端 未结 11 823
误落风尘
误落风尘 2020-12-04 11:57

I created an app and I am attempting to allow the user to continue to listen to their music while playing my game, but whenever they hit \"play\" and the ingame sounds occur

相关标签:
11条回答
  • 2020-12-04 12:39

    For Swift (Objective-C like this too)

    you can use this link for best answer and if you don't have any time for watching 10 minutes the best action is that you just copy below code in your AppDelegate in didFinishLaunchingWithOptions and then select your project's target then go to Capabilities and at last in Background modes check on Audio, AirPlay and Picture in Picture

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
    
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(AVAudioSessionCategoryPlayback)
        }
        catch {
    
        }
    }
    
    0 讨论(0)
  • 2020-12-04 12:42

    I didn't think that just setting the AVAudioSession to AVAudioSessionCategoryOptions.duckOthers would work, but it did. Here is my full code to help the rookies like myself.

    Swift 4 - Full Example:

    var audioPlayer = AVAudioPlayer()
    
    
    func playSound(sound: String){
        let path = Bundle.main.path(forResource: sound, ofType: nil)!
        let url = URL(fileURLWithPath: path)
    
        let audioSession = AVAudioSession.sharedInstance()
        try!audioSession.setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.duckOthers)
    
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer.play()
        } catch {
            print("couldn't load the file")
        }
    }
    

    I still need to figure out setActive (I was looking at this blog post) but the audio stops ducking when I leave the app, so it works for my app.

    0 讨论(0)
  • 2020-12-04 12:44

    This is how I do it in Swift 3.0

    var songPlayer : AVAudioPlayer?         
    
    func SetUpSound() {
    
    
            if let path = Bundle.main.path(forResource: "TestSound", ofType: "wav") {
                let filePath = NSURL(fileURLWithPath:path)
                songPlayer = try! AVAudioPlayer.init(contentsOf: filePath as URL)
                songPlayer?.numberOfLoops = -1 //logic for infinite loop
                songPlayer?.prepareToPlay()
                songPlayer?.play()
            }
    
            let audioSession = AVAudioSession.sharedInstance()
            try!audioSession.setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.duckOthers) //Causes audio from other sessions to be ducked (reduced in volume) while audio from this session plays  
    }
    

    You can see more of AVAudioSessionCategoryOptions here: https://developer.apple.com/reference/avfoundation/avaudiosessioncategoryoptions

    0 讨论(0)
  • 2020-12-04 12:45

    Swift 4 version:

    try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
    try? AVAudioSession.sharedInstance().setActive(true)
    
    0 讨论(0)
  • 2020-12-04 12:47

    Since they can't seem to make up their minds from version to version. Here it is in Swift 5.0

    do{
       try AVAudioSession.sharedInstance().setCategory(.ambient)
       try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
    } catch {
       NSLog(error.localizedDescription)
    }
    
    0 讨论(0)
  • 2020-12-04 12:48

    Here's what I am using for Swift 2.0:

    let sess = AVAudioSession.sharedInstance()
    if sess.otherAudioPlaying {
        _ = try? sess.setCategory(AVAudioSessionCategoryAmbient, withOptions: .DuckOthers)
        _ = try? sess.setActive(true, withOptions: [])
    }
    

    Please note that you can replace .DuckOthers with [] if you don't want to lower background music and instead play on top to it.

    0 讨论(0)
提交回复
热议问题