利用 AVAudioPlayer 或 AVPlayer 播放 App 裡的 mp3 檔
Published in
3 min readJul 25, 2018
想播放 App 裡的音檔,我們可以選擇用 AVAudioPlayer 或 AVPlayer 播放。( 如果是網路上的音樂,則建議用 AVPlayer ) 方法如下:
1 將 mp3 檔加入 Xcode 專案。
加入檔案時記得要勾選 Copy items if needed。
2 利用 AVAudioPlayer 播放。
import UIKitimport AVFoundation
class ViewController: UIViewController { var player: AVAudioPlayer? @IBAction func playMusic(_ sender: Any) { if let url = Bundle.main.url(forResource: "Rolling A Dice", withExtension: "mp3") { player = try? AVAudioPlayer(contentsOf: url) player?.play() } }}
說明
Bundle.main.url(forResource: "Rolling A Dice", withExtension: "mp3")
利用 Bundle.main 得到主要的 Bundle 物件,可用來讀取專案裡的檔案。呼叫它的 function url(forResource:withExtension:) 可得到檔案路徑的 URL。
3 利用 AVPlayer 播放。
import UIKitimport AVFoundationclass ViewController: UIViewController { var player: AVPlayer? @IBAction func buttonPressed(_ sender: Any) { if let url = Bundle.main.url(forResource: "Rolling A Dice", withExtension: "mp3") { player = AVPlayer(url: url) player?.play() }}
如果還不懂 optional binding 的同學,則可先用 ! 讀取 function url(forResource:withExtension:) 回傳的 optional 路徑。
import AVFoundationclass ViewController: UIViewController { var player: AVPlayer? @IBAction func buttonPressed(_ sender: Any) { url = Bundle.main.url(forResource: "Rolling A Dice", withExtension: "mp3")! player = AVPlayer(url: url) player?.play()}