当我的应用程序在使用Swift时仍然播放其声音时,如何允许继续播放背景音乐

时间:2015-03-13 03:17:32

标签: ios xcode swift audio mobile

我创建了一个应用程序,我试图让用户在玩游戏的同时继续听他们的音乐,但每当他们点击"播放"并且发出游戏声音会停止背景音乐。我正在使用Swift在iOS上进行开发。这是启动游戏声音的一段代码。

func playSpawnedDot() {
    var alertSound: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("spawnDot", ofType: "mp3")!)!
    var error:NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
    audioPlayer.prepareToPlay()

    if volumeBool {
        audioPlayer.play()
    }
}

13 个答案:

答案 0 :(得分:46)

您需要使用以下值之一设置AVAudioSession类别:https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/index.html(AVAudioSession类参考)。

默认值设置为AVAudioSessionCategorySoloAmbient。你可以读到:

  

[...]使用此类别意味着您的应用程序的音频不可混合 - 激活您的会话将中断任何其他也不可混合的音频会话。要允许混音,请改用AVAudioSessionCategoryAmbient类别。

在播放声音之前,您必须更改类别。为此:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

每次播放声音时都不需要拨打这些线路。您可能只想做一次。

答案 1 :(得分:14)

Swift 4 版本:

try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try? AVAudioSession.sharedInstance().setActive(true)

答案 2 :(得分:12)

这就是我在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  
}

您可以在此处查看更多AVAudioSessionCategoryOptions:https://developer.apple.com/reference/avfoundation/avaudiosessioncategoryoptions

答案 3 :(得分:9)

这是我用于Swift 2.0的内容:

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

请注意,如果您不想降低背景音乐,请将.DuckOthers替换为[]

答案 4 :(得分:5)

lchamp的解决方案非常适合我,适用于Objective-C:

{{1}}

答案 5 :(得分:2)

**

更新了Swift 3.0

**

我正在播放的声音的名称是shatter.wav

func shatterSound() {
    if let soundURL = Bundle.main.url(forResource: "shatter", withExtension: "wav") {
        var mySound: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
        AudioServicesPlaySystemSound(mySound);
    }
}

然后你想在哪里播放声音

shatterSound()

答案 6 :(得分:2)

如果您想播放提示音:

public func playSound(withFileName fileName: String) {

    if let soundUrl = Bundle.main.url(forResource: fileName, withExtension: "wav") {
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, with:[.duckOthers])
            try AVAudioSession.sharedInstance().setActive(true)

            var soundId: SystemSoundID = 0

            AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundId)
            AudioServicesAddSystemSoundCompletion(soundId, nil, nil, { (soundId, clientData) -> Void in
                AudioServicesDisposeSystemSoundID(soundId)
                do {
                    // This is to unduck others, make other playing sounds go back up in volume
                    try AVAudioSession.sharedInstance().setActive(false)
                } catch {
                    DDLogWarn("Failed to set AVAudioSession to inactive. error=\(error)")
                }
            }, nil)

            AudioServicesPlaySystemSound(soundId)
        } catch {
            DDLogWarn("Failed to create audio player. soundUrl=\(soundUrl) error=\(error)")
        }
    } else {
        DDLogWarn("Sound file not found in app bundle. fileName=\(fileName)")
    }
}

如果你想播放音乐:

导入AVFoundation

var audioPlayer:AVAudioPlayer?

public func playSound(withFileName fileName: String) {

    if let soundUrl = Bundle.main.url(forResource: fileName, withExtension: "wav") {
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, with:[.duckOthers])
            try AVAudioSession.sharedInstance().setActive(true)

            let player = try AVAudioPlayer(contentsOf: soundUrl)
            player.delegate = self
            player.prepareToPlay()
            DDLogInfo("Playing sound. soundUrl=\(soundUrl)")
            player.play()
            // ensure the player does not get deleted while playing the sound
            self.audioPlayer = player
        } catch {
            DDLogWarn("Failed to create audio player. soundUrl=\(soundUrl) error=\(error)")
        }
    } else {
        DDLogWarn("Sound file not found in app bundle. fileName=\(fileName)")
    }
}

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    self.audioPlayer?.stop()
    do {
        // This is to unduck others, make other playing sounds go back up in volume
        try AVAudioSession.sharedInstance().setActive(false)
    } catch {
        DDLogWarn("Failed to set AVAudioSession inactive. error=\(error)")
    }
}

答案 7 :(得分:1)

对于Swift(Objective-C也是这样)

您可以使用this链接获得最佳答案,如果您没有时间观看10分钟,那么最佳操作就是copy以下AppDelegate中的代码didFinishLaunchingWithOptions,然后选择project's target,然后转到Capabilities,最后在Background modes检查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 {

    }
}

答案 8 :(得分:0)

我认为仅将AVAudioSession设置为AVAudioSessionCategoryOptions.duckOthers不会起作用,但确实如此。这是我的完整代码,可以帮助像我这样的菜鸟。

快速4-完整示例

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")
    }
}

我仍然需要弄清楚setActive(I was looking at this blog post),但是当我离开应用程序时,音频会停止回避,因此适用于我的应用程序。

答案 9 :(得分:0)

因为他们似乎无法决定版本之间的关系。这就是Swift 5.0

do{
   try AVAudioSession.sharedInstance().setCategory(.ambient)
   try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
} catch {
   NSLog(error.localizedDescription)
}

答案 10 :(得分:0)

基于lchamp答案的Swift 5版本。

try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)
try? AVAudioSession.sharedInstance().setActive(true)

答案 11 :(得分:0)

这在 iOS 14.4 和 Swift 5 上非常适合我。通过使用 .duckOthers 选项,它与其他人的答案略有不同(如果您愿意,也可以直接与声音混合使用 .mixWithOthers),但它在播放音乐时效果很好。它将降低音乐音量,播放“哔”声,然后将音乐音量调高至正常。如果出现问题,它还会使用 Google Firebase Crashlytics 捕获错误数据,并尝试在出现错误时将音量提高到正常水平。

此代码也可以在第一次和所有其他声音播放时完美运行,而不会停止音乐。

func playSound() {
    do {
        if let path = Bundle.main.path(forResource: "beep", ofType: "mp3") {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .duckOthers)
            try AVAudioSession.sharedInstance().setActive(true)
            
            let filePath = NSURL(fileURLWithPath:path)
            songPlayer = try AVAudioPlayer.init(contentsOf: filePath as URL)
            songPlayer?.numberOfLoops = 0
            songPlayer?.prepareToPlay()
            songPlayer?.play()
            
            try AVAudioSession.sharedInstance().setActive(false)
        }
    } catch (let error) {
        try? AVAudioSession.sharedInstance().setActive(false)
        Crashlytics.crashlytics().setCustomValue(error.localizedDescription, forKey: "audio_playback_error")
    }
}

答案 12 :(得分:0)

其他人的答案没有的一个重要的事情是,您需要在停用时使用 .notifyOthers 标志调用 false:

try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)

这样做的原因是其他在后台播放音乐的应用程序会在您停用您的应用程序时知道何时重新打开它们的音频。否则,如果您关闭会话,您的背景音乐将不会重新打开。