ios – “尝试?”和AVAudioPlayer的问题

前端之家收集整理的这篇文章主要介绍了ios – “尝试?”和AVAudioPlayer的问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对AVAudioPlayer有以下问题:
import Foundation   //Needed for dispatch_once_t
import AVFoundation //Needed to play sounds

class PlayStartSong {

    var song: AVAudioPlayer = AVAudioPlayer()
    var songStarted: Bool = false

    class var sharedInstance: PlayStartSong {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: PlayStartSong? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = PlayStartSong()
        }
        return Static.instance!
    }

    func prepareAudios() {

        var path = NSBundle.mainBundle().pathForResource("start-2.0",ofType: "mp3")
        song = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))    //Error Here
        song.prepareToPlay()

        song.numberOfLoops = -1 //Makes the song play repeatedly
    }
}

在“prepareAudios”函数中指定变量“song”的值的行上,转换为Swift 2.0后出现以下错误

Value of optional type ‘AVAudioPLayer?’ not unwrapped; did you mean to use ‘!’ or ‘?’?

但是,在使用建议的修复程序时,它告诉我删除刚刚添加的感叹号.这里的确切问题是什么?

解决方法

试试用?如您所愿,您的歌曲变量必须是可选的:
class PlayStartSong {

    var song: AVAudioPlayer?
    var songStarted: Bool = false

    class var sharedInstance: PlayStartSong {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: PlayStartSong? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = PlayStartSong()
        }
        return Static.instance!
    }

    func prepareAudios() {
        let path = NSBundle.mainBundle().pathForResource("start-2.0",ofType: "mp3")
        song = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
        song?.prepareToPlay()
        song?.numberOfLoops = -1 //Makes the song play repeatedly
    }
}

要不使它成为Optional,你可以使用try inside do catch:

func prepareAudios() {
    do {
        let path = NSBundle.mainBundle().pathForResource("start-2.0",ofType: "mp3")
        song = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
        song.prepareToPlay()
        song.numberOfLoops = -1 //Makes the song play repeatedly
    } catch {
        print(error)
    }
}

此外,如果您完全确定创建AVAudioPlayer实例将始终成功,则可以使用try!忽略“do catch”:

func prepareAudios() {
    let path = NSBundle.mainBundle().pathForResource("start-2.0",ofType: "mp3")
    song = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
    song.prepareToPlay()
    song.numberOfLoops = -1 //Makes the song play repeatedly
}

猜你在找的iOS相关文章