點擊 Play 按鈕,播放音樂,必且在下方顯示進度與歌曲秒數。
要完成
- Play Button
- Label 顯示秒數進度
- Slider 進度顯示
// | |
// ViewController.swift | |
// PlayMusic | |
// | |
// Created by Edward Chiang on 15/11/2016. | |
// Copyright © 2016 TKU. All rights reserved. | |
// | |
import UIKit | |
import AVFoundation | |
class ViewController: UIViewController { | |
@IBOutlet weak var progressTimeLabel: UILabel! | |
@IBOutlet weak var playMusicButton: UIButton! | |
@IBOutlet weak var slider: UISlider! | |
var myPlayer : AVAudioPlayer = AVAudioPlayer() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
let filePath = Bundle.main.path(forResource: "victory-will-be-ours-epic-grip", ofType: "mp3") | |
do { | |
let url = NSURL(fileURLWithPath: filePath!) | |
self.myPlayer = try AVAudioPlayer(contentsOf: url as URL) | |
// Other player can play music in background. | |
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) | |
try AVAudioSession.sharedInstance().setActive(true) | |
} catch { | |
print("Error!") | |
} | |
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {(timer) -> Void in | |
self.progressTimeLabel.text = String(format: "%.0f/%.0f", self.myPlayer.currentTime, self.myPlayer.duration) | |
self.slider.value = Float(self.myPlayer.currentTime) | |
}) | |
self.slider.maximumValue = Float(self.myPlayer.duration) | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
@IBAction func playButtonClicked(_ sender: Any) { | |
if self.myPlayer.isPlaying == false { | |
self.myPlayer.play() | |
self.playMusicButton.setTitle("Pause", for: .normal) | |
} else { | |
self.myPlayer.pause() | |
self.playMusicButton.setTitle("Play", for: .normal) | |
} | |
} | |
@IBAction func sliderChanged(_ sender: Any) { | |
self.myPlayer.currentTime = Double(self.slider.value) | |
} | |
} |