Swift 背景音乐

Swift music in background

我正在使用以下函数在我的应用程序中播放音效。我想做到这一点,以便用户可以同时收听他们的 iphone 音乐。

我也在多个视图控制器上使用它..不确定这是否会改变任何东西。完成此操作的最简单方法是什么?

var audioPlayer = AVAudioPlayer()
func playSound (Sound: String, Type: String) {

    let path = NSBundle.mainBundle().pathForResource(Sound, ofType: Type)!
    let url = NSURL(fileURLWithPath: path)

    do {
        let sound = try AVAudioPlayer(contentsOfURL: url)
        audioPlayer = sound
        sound.play()
    } catch {
        // couldn't load file :(
    }
}

你可以做到

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

更新:

请记住在执行此操作的文件中 import AVFoundation 并使用错误处理,因为此方法会抛出。

它可以用在类似这样的地方,例如向上传递处理错误的责任。

import AVFoundation

func configureAudioSession() throws {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
}

或者如果不想处理错误(不推荐),像这样:

_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

您只需执行此操作一次(因为我们正在访问 sharedInstance()),因此无论何时配置音频会话都是执行此操作的好地方。

如果您要创建更多 AVAudioSession,则需要为每个音频会话执行此操作。