iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 14
0
Software Development

30天Swift入門學習系列 第 14

iOS App 實作(11)音樂播放(AVAudioPlayer)


Description:
此demo為一音樂播放器,裡面功能包含了播放、暫停、重置音樂。另外可透過slider bar來調整音樂進度和音量。


Component:

  1. AVAudioPlayer
  2. UISlider

Highlight function:
Swift 音樂播放或錄音功能是屬於 AVFoundation library,因此在使用時需先 import 此 library:

import AVFoundation

因本篇是討論播放功能,故只需宣告 AVAudioPlayer 即可。在此 demo 中是播放是先存放好的音樂檔案,宣告及取得檔案方式如下:

var audioPlayer: AVAudioPlayer!

let url = Bundle.main.url(forResource: "ISeeFire", withExtension: "mp3")    
do {
  audioPlayer = try AVAudioPlayer(contentsOf: url!)
  audioPlayer.prepareToPlay()
} catch {
  print("Error:", error.localizedDescription)
}

AVAudioPlayer 的播放、暫停及停止其指令相當簡單,如下:

audioPlayer.play()
audioPlayer.pause()
audioPlayer.stop()

透過上述三個功能來實作播放、暫停及停止:

  1. 播放。在此透過一 Timer 來更新音樂進度條:
@IBAction func palyBtnAction(sender: AnyObject) {
  audioPlayer.play()

  if progressTimer == nil {
    progressTimer = Timer.scheduledTimer(timeInterval: 1,
                                         target: self,
                                         selector: #selector(PlayerVC.updateProgressSlider),
                                         userInfo: nil,
                                         repeats: true)
    }
  }
  1. 暫停。暫停時須停止進度條更新:
@IBAction func pauseBtnAction() {
  stopTimeInterval()
  audioPlayer.pause()
}
  1. 停止。由於 AVAudioPlayer 在執行 stop() 時只是釋放播放聲音之硬體的控制權並不會把播放進度重置,這方面可透過 AVAudioPlayer 本身的 currentTime property 來自行重置:
@IBAction func stopBtnAction() {
  stopTimeInterval()
  audioPlayer.stop()
  audioPlayer.currentTime = 0 // reset player time offset
  musicProgress.value = 0
}

使用 slider bar 來改變 AVAudioPlayer 本身的 volume property 以調整音樂大小:

audioPlayer.volume = UISlider.value

Additional:
在拖動音樂進度條時,為了讓拖動時音樂能繼續播放並在使用者手放開後才更新音樂播放進度。在此 demo 中使用touchUpInside 此 event 來完成上述動作。

musicProgress.addTarget(self,
                            action: #selector(PlayerVC.progressChangeAct),
                            for: .touchUpInside)

Reference:
Source code on Github


上一篇
Access Control in Swift
下一篇
iOS App 實作(12)錄音功能(AVAudioRecorder)
系列文
30天Swift入門學習30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言