UI制作播放器(入门)

用swift编写程序,实现但首歌曲播放(附带暂停和继续播放功能)。

import UIKit
import AVFoundation    
classViewController:UIViewController,AVAudioPlayerDelegate 
{
    @IBOutlet weak var jindu: UIProgressView! //添加进度按钮
    var bz = false
    var audio : AVAudioPlayer?        //定义播放器
    var timer : NSTimer?              //定义定时器

    override func viewDidLoad() {
        super.viewDidLoad()
          
            //尝试播放,如果没错误就播放
            let url = NSBundle.mainBundle().URLForResource("后会无期", withExtension: "mp3")
            try! audio = AVAudioPlayer(contentsOfURL: url!)
       }

    @IBAction func play(sender: UIButton) {
        do  {
              //加速
            audio?.enableRate = true
            audio?.rate = 10
            
            audio?.prepareToPlay()
            audio?.play()

            print(audio?.duration)
            audio?.delegate = self
            //创建一个定时器
            timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(did(_:)), userInfo: nil, repeats: true)
        }
        catch let error as NSError{
            print(error.code,error.localizedDescription)
        }

        //创建循环,控制暂停开始
            if bz {
                pause1()
                bz = false
            }
    
            else {
                play1()
                bz = true
            }
        }
    
    func pause1(){
        audio?.pause()
    }
    func play1(){
        audio?.play()
    }
//输出进度   
    func did(timer: NSTimer) {
        print("\(audio?.currentTime)s")
        print("\((audio?.currentTime)! / (audio?.duration)!)")
        jindu.progress = Float((audio?.currentTime)! / (audio?.duration)!)
    }
    
//告诉系统播放完毕
      func audioPlayerDidFinishPlaying(player:AVAudioPlayer,successfully flag:Bool) {
        print("播放完成")
    }
}

你可能感兴趣的:(UI制作播放器(入门))