问题:
当我转向持有按钮和滑块的viewcontroller时,它会崩溃应用程序并在{{1}行上给我线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x38) }。在视图控制器中,我有一个播放/暂停按钮,一个停止按钮和一个控制音频播放位置的滑块。
代码:
slider.maximumValue = Float(audioPlayer.duration)
答案 0 :(得分:5)
解决了这个问题:
import UIKit
import AVFoundation
class AgnesAudioViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
var toggleState = 1
@IBOutlet var slider: UISlider!
@IBOutlet var playedTime: UILabel!
@IBAction func done(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
audioPlayer.stop()
}
@IBAction func play(sender: AnyObject) {
audioPlayer.play()
updateTime()
}
@IBAction func pause(sender: AnyObject) {
audioPlayer.pause()
updateTime()
}
@IBAction func stop(sender: AnyObject) {
audioPlayer.stop()
updateTime()
}
@IBAction func scrubAudio(sender: AnyObject) {
audioPlayer.stop()
audioPlayer.currentTime = NSTimeInterval(slider.value)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
func updateTime() {
var currentTime = Int(audioPlayer.currentTime)
var duration = Int(audioPlayer.duration)
var total = currentTime - duration
var totalString = String(total)
var minutes = currentTime/60
var seconds = currentTime - minutes / 60
playedTime.text = NSString(format: "%02d:%02d", minutes,seconds) as String
}
@IBAction func playPauseButton(sender: AnyObject) {
//1 = play
//2 = pausw
var playBtn = sender as! UIButton
if toggleState == 1 {
audioPlayer.play()
toggleState = 2
playBtn.setImage(UIImage(named:"pause2.png"),forState:UIControlState.Normal)
} else {
audioPlayer.pause()
toggleState = 1
playBtn.setImage(UIImage(named:"play2.png"),forState:UIControlState.Normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
var updateTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
var timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateSlider"), userInfo: nil, repeats: true)
let pathString = NSBundle.mainBundle().pathForResource("agnes", ofType: "mp3")
if let pathString = pathString {
let pathURL = NSURL(fileURLWithPath: pathString)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: pathURL)
} catch {
print("error")
}
}
slider.maximumValue = Float(audioPlayer.duration)
}
func updateSlider() {
slider.value = Float(audioPlayer.currentTime)
}
}
答案 1 :(得分:3)
对于 Hunter的答案 ,它可以,但我会在updateTime
函数中添加一些行。因为像这样它在标签上没有显示像1:61那样的时间。
func updateTime() {
var currentTime = Int(audioPlayer.currentTime)
var duration = Int(audioPlayer.duration)
var total = currentTime - duration
var totalString = String(total)
var minutes = currentTime/60
var seconds = currentTime - minutes / 60
if minutes > 0 {
seconds = seconds - 60 * minutes
}
playedTime.text = NSString(format: "%02d:%02d", minutes,seconds) as String
}