【问题标题】:Playing audio file in Swift using AVPlayer使用 AVPlayer 在 Swift 中播放音频文件
【发布时间】:2016-09-20 19:50:08
【问题描述】:

我有一个非常简单的方法可以使用AVPlayer 在 Swift 中播放 mp3 音频文件。

问题是,这似乎太简单了。例如,在播放出现问题、文件出现问题、设备音频出现问题的情况下,如何才能优雅地播放失败而不是应用崩溃?

或者下面的播放代码安全吗?

import UIKit

import AVFoundation

var audioPlayer:AVPlayer!

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        audioPlayer = AVPlayer(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("myResourceFileName", ofType: "mp3")!))
        audioPlayer.play()

    }

}

【问题讨论】:

  • 使用 if let 语句测试 pathForResource。不要强制解包。

标签: ios swift optimization avfoundation avplayer


【解决方案1】:

为什么不试试“Do”和“Catch”呢?

do {let path = NSBundle.mainBundle().pathForResource("myResourceFileName", ofType: "mp3")
     let soundUrl = NSURL(fileURLWithPath: path!)
     try audioPlayer = AVAudioPlayer(contentsOfURL: soundUrl)
         audioPlayer.prepareToPlay()            
   } catch let err as NSError {
       print(err.debugDescription)
   }

并放置 音频播放器.play() 在你想玩的功能上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2011-11-15
    • 2019-08-20
    相关资源
    最近更新 更多