简体   繁体   中英

I want to make sound effects without stopping the music playing in the background in another app

I am currently developing an application with SwiftUI. There is a function that plays a sound effect when you tap on it. When I tested it on the actual device, the Spotify music playing in the background stopped. Is it possible to use AVFoundation to play sound effects without stopping the music? Also, if there is a better way to implement this, please help me.

import Foundation
import AVFoundation

var audioPlayer: AVAudioPlayer?

func playSound(sound: String, type: String) {

    if let path = Bundle.main.path(forResource: sound, ofType: type) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            audioPlayer?.play()

           
        } catch {
            print("ERROR:Could not find and play the sound file.")
        }
       
    }
}

Set your AVAudioSession category options to .mixWithOthers .

let audioSession = AVAudioSession.sharedInstance()
do {
    try audioSession.setCategory(.ambient, mode: .default, options: [.mixWithOthers])
} catch {
    print("Failed to set audio session category.")
}

audioSession.setActive(true) // When you're ready to play something

ambient indicates that sound is not critical to this application. The default is soloAmbient , which is non-mixable. (It's possible you can just set the category to ambient here and you'll get mixWithOthers for free. I don't often use that mode, so I don't remember how much you get by default.) If sound is critical, see the mode .playback .

As a rule, you set the category once in the app, and then set the session active or inactive as you need it. If I remember correctly, AVAudioPlayer will automatically activate the session, so you may not need to do that (I typically work at much lower levels, and don't always remember what the high-level tools do automatically). It is legal to change your category, however, if different features of your app have different needs.

For more details, see AVAudioSession.Category and AVAudioSession . There are many options in sound playback, and many of them are not obvious (and a few have very confusing names, I'm looking at you .allowBluetooth ), so it's worth reading through the docs.

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