美文网首页程序员iOS Developer
iOS Swift 3&4 简单易懂的Recipes系列

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

作者: 荷兰豆子Sweetkoto | 来源:发表于2017-08-12 01:36 被阅读43次

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

    相关文章

      网友评论

        本文标题:iOS Swift 3&4 简单易懂的Recipes系列

        本文链接:https://www.haomeiwen.com/subject/bfddrxtx.html