目前分類:多媒體應用 (2)

瀏覽方式: 標題列表 簡短摘要

此篇文播放影片之範例程式, 在storyBoard須先行設定一Button

Will 發表在 痞客邦 留言(0) 人氣()

此專案為播放音樂之程式, 使用一個label顯示歌曲長度, slider可調整歌曲進度, 最後點擊Btn播放音樂以及停止

import UIKit
import AVFoundation

class ViewController: UIViewController {

    
    @IBOutlet weak var playMusicButtom: UIButton!
    @IBOutlet weak var mySlider: UISlider!
    @IBOutlet weak var progressTimeLabel: UILabel!
    
    var myPlayer = AVAudioPlayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let filePath = NSBundle.mainBundle().pathForResource("ur music in project", ofType: "mp3")
        
        do
        {
            myPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: filePath!))
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
            try AVAudioSession.sharedInstance().setActive(true)
        }
        catch
        {
            print("error")
        }
        
        NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.playingProgress), userInfo: nil, repeats: true) //每秒更新slider
        mySlider.maximumValue = Float(myPlayer.duration) //取得歌曲總長度
    }
    
    func playingProgress() //顯示歌曲長度
    {
        progressTimeLabel.text = String(format: "%.0f/%.0f", myPlayer.currentTime, myPlayer.duration)
        mySlider.value = Float(myPlayer.currentTime)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func playMusicButtom(sender: AnyObject) //檢查playBtn之狀態
    {
        if myPlayer.playing == false
        {
            myPlayer.play()
            playMusicButtom.setTitle("pause", forState: .Normal)
        }else{
            myPlayer.pause()
            playMusicButtom.setTitle("play", forState: .Normal)
        }
    }

    @IBAction func mySlider(sender: AnyObject) //調整slider移動歌曲進度
    {
        myPlayer.currentTime = Double(mySlider.value)
    }
}


文章標籤

Will 發表在 痞客邦 留言(0) 人氣()