程序员iOS Developer

iOS Swift 3&4 简单易懂的Recipes系列

2017-08-12  本文已影响43人  荷兰豆子Sweetkoto

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

    do {
    audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
    }
    catch {
    print(error)
    }

//第六步:调用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. 谢谢配合~)

上一篇下一篇

猜你喜欢

热点阅读