gpt4 book ai didi

ios - "try?"和 AVAudioPlayer 问题

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:39:15 24 4
gpt4 key购买 nike

我在使用 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 '?'?

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

最佳答案

要按预期使用 try?,您的 song 变量必须是可选的:

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

为了不让它成为可选的,你可以在 do catch 中使用 try:

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 - "try?"和 AVAudioPlayer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com