声音返回 Swift
Sound go back with Swift
我可以在单击按钮时播放声音。我可以找到这个并且它与游戏配合得很好:
var sound1 = AVAudioPlayer()
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
var path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
var url = NSURL.fileURLWithPath(path!)
var error: NSError?
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
return audioPlayer!
}
@IBAction func play(sender: AnyObject) {
soun1.play()
}
在 viewDidLoad 中:
sound1 = self.setupAudioPlayerWithFile("NameAudioFile", type:"mp3")
如何从当前时间返回 30 秒?
@IBAction func back(sender: AnyObject) {
...
}
您可以使用 Swift 三元条件运算符 '?'您检查 currentTime 是否 > 30 ?如果为真减去 30 :否则等于 0
sound1.currentTime = sound1.currentTime > 30.0 ? sound1.currentTime - 30.0 : 0
编辑
正如 OP 所指出的,只需从 currentTime 中减去 30s,因为它将负值视为零:
sound1.currentTime = sound1.currentTime - 30.0
The ternary conditional operator is a special operator with three
parts, which takes the form question ? answer1 : answer2. It is a
shortcut for evaluating one of two expressions based on whether
question is true or false. If question is true, it evaluates answer1
and returns its value; otherwise, it evaluates answer2 and returns its
value.
我可以在单击按钮时播放声音。我可以找到这个并且它与游戏配合得很好:
var sound1 = AVAudioPlayer()
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
var path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
var url = NSURL.fileURLWithPath(path!)
var error: NSError?
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
return audioPlayer!
}
@IBAction func play(sender: AnyObject) {
soun1.play()
}
在 viewDidLoad 中:
sound1 = self.setupAudioPlayerWithFile("NameAudioFile", type:"mp3")
如何从当前时间返回 30 秒?
@IBAction func back(sender: AnyObject) {
...
}
您可以使用 Swift 三元条件运算符 '?'您检查 currentTime 是否 > 30 ?如果为真减去 30 :否则等于 0
sound1.currentTime = sound1.currentTime > 30.0 ? sound1.currentTime - 30.0 : 0
编辑
正如 OP 所指出的,只需从 currentTime 中减去 30s,因为它将负值视为零:
sound1.currentTime = sound1.currentTime - 30.0
The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2. It is a shortcut for evaluating one of two expressions based on whether question is true or false. If question is true, it evaluates answer1 and returns its value; otherwise, it evaluates answer2 and returns its value.