iOS Swift 3&4 簡單易懂的Recipes系列 - 使用AVFoundation的AVAudioPlayer播放本地音頻文件

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.

簡單翻譯過來就是:
  1. 用于播放本地音頻
  2. 不推薦用于播放網絡音頻
  3. 要求超低延遲時不推薦使用

更多詳情見:幫助文檔 From Apple

Recipe:


//第一步:導入AVFoundation

import UIKit
import AVFoundation

//第二步:添加AVAudioPlayerDelegateUIViewController 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在讀取URLthrow errors所以要用這個形式來把可能會出現的errorcatch抓住
    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. 謝謝配合~)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容