Note from Apple:
AVAudioPlayer
An instance of the AVAudioPlayer class, called an audio player, provides playback of audio data from a file or memory.
Apple recommends that you use this class for audio playback unless you are playing audio captured from a network stream or require very low I/O latency.
簡單翻譯過來就是:
- 用于播放本地音頻
- 不推薦用于播放網絡音頻
- 要求超低延遲時不推薦使用
更多詳情見:幫助文檔 From Apple
Recipe:
//第一步:導入AVFoundation
import UIKit
import AVFoundation
//第二步:添加AVAudioPlayerDelegate
到UIViewController
class
class UIViewController : UIViewController, AVAudioPlayerDelegate {
}
//第三步:創建audioPlayer
container(variable)
var audioPlayer : AVAudioPlayer!
//第四步:創建音頻的URL
let soundURL = Bundle.main.url(forResource: "音頻名字", withExtension: "音頻格式 e.g. mp3")
//第五步:使用do{try} catch{}
來讓 audioPlayer
使用剛剛創建的URL
- 因為
AVAudioPlayer
在讀取URL
會throw
errors
所以要用這個形式來把可能會出現的error
用catch
抓住
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
- 如果100%確定本地的音頻文件一定不會有問題,可以不使用
do{try} catch{}
這個形式,直接在try后面加!來達到同樣的效果,如:audioPlayer = try! AVAudioPlayer(contentsOf: soundURL!)
//第六步:調用play()
來播放音頻
audioPlayer.play()
Example:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func buttonTapped(_ sender: UIButton) {
playSound(soundFileName : "喵", soundExtension: "m4a")
}
func playSound(soundFileName : String, soundExtension: String) {
let soundURL = Bundle.main.url(forResource: soundFileName, withExtension: soundExtension)
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
} catch {
print(error)
}
audioPlayer.play()
}
}
參考Demo:PlaySound Demo on GitHub
(Demo內所有素材版權歸@lovelyhelenzhu所有,禁止一切二次修改、轉載etc. 謝謝配合~)