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. 谢谢配合~)