Skip to content

Instantly share code, notes, and snippets.

@edwardinubuntu
Last active November 22, 2016 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardinubuntu/5864e8d6d44694fbfd54df717d09a935 to your computer and use it in GitHub Desktop.
Save edwardinubuntu/5864e8d6d44694fbfd54df717d09a935 to your computer and use it in GitHub Desktop.
tibame.com iOS Swift 播放音樂

播放音樂

點擊 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment