UI播放器 实现播放功能
import UIKit
import AVFoundation //加入影音架构
class ViewController: UIViewController, AVAudioPlayerDelegate {
@IBOutlet weak var progress: UIProgressView! //把进度条关联进来
var audioPlayer: AVAudioPlayer? //关联播放器
var timer: NSTimer? //关联定时器,进度条有用
@IBAction func play(sender: AnyObject) { //把play按钮关联进来
let url = NSBundle.mainBundle().URLForResource("小苹果唢呐版", withExtension: "mp3") //写上歌曲名称和格式类型
do {
//Swift需要明确表明可能出异常语句
try audioPlayer = AVAudioPlayer(contentsOfURL: url!)
// audioPlayer?.enableRate = true
// audioPlayer?.rate = 10 //播放速率
audioPlayer?.prepareToPlay()
audioPlayer?.play()
print(audioPlayer?.duration)
audioPlayer?.delegate = self
//创建一个 timer 定时器,并且开始运行
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(didTime(_:)), userInfo: nil, repeats: true)
}
catch let error as NSError {
print(error.code, error.localizedDescription)
}
}
@IBAction func stop(sender: AnyObject) {
timer?.invalidate()
audioPlayer?.pause() //关联停止按钮,实现暂停功能
}
func didTime(timer: NSTimer) {
print("\(audioPlayer?.currentTime)s")
print("\((audioPlayer?.currentTime)! / (audioPlayer?.duration)!)")
//计算进度
progress.progress = Float((audioPlayer?.currentTime)! / (audioPlayer?.duration)!) //progress为进度条名字,后面是换算方法
// progressView.progress
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag:Bool) {
print("播放完成")
}
}