xcode 如何使用 swift 2.0 播放背景音乐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32882737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:58:56  来源:igfitidea点击:

How to play background music with swift 2.0?

iosxcodeswiftswift2

提问by H Sefein

HI I am new to swift and ios development. My code was working up until I've updated to Swift 2.0, I've used swift migrating tool, but I still can't figure out how to sort and fix my code. Please help!

嗨,我是 swift 和 ios 开发的新手。我的代码一直在运行,直到我更新到 Swift 2.0,我已经使用了 swift 迁移工具,但我仍然不知道如何对我的代码进行排序和修复。请帮忙!

import AVFoundation

var backgroundMusicP: AVAudioPlayer!

func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(
        filename, withExtension: nil)
    if (url == nil) {
        print("Could not find file: \(filename)")
        return
    }

    var error: NSError?

    do {

        backgroundMusicP = try AVAudioPlayer(contentsOfURL: url!)
    } catch {

        backgroundMusicP == nil
    }
    if backgroundMusicP == nil {
        print("Could not create audio player: \(error)")
        return
    }

    backgroundMusicP.numberOfLoops = -1
    backgroundMusicP.prepareToPlay()
    backgroundMusicP.play()
}

回答by Dharmesh Kheni

Updated function for swift 2.0:

Swift 2.0 的更新功能:

import AVFoundation

var backgroundMusicPlayer = AVAudioPlayer()

func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
    guard let newURL = url else {
        print("Could not find file: \(filename)")
        return
    }
    do {
        backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
        backgroundMusicPlayer.numberOfLoops = -1
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    } catch let error as NSError {
        print(error.description)
    }
}

Use it this way:

以这种方式使用它:

playBackgroundMusic("yourFileName.mp3")

回答by Tapas Pal

You can enable a session also for background playing capability.

您还可以为后台播放功能启用会话。

func enableBackgroundPlaying(_ enable: Bool) throws {
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        do {
            try AVAudioSession.sharedInstance().setActive(enable)
        } catch {
            throw error
        }
    } catch {
        throw error
    }
}