gpt4 book ai didi

ios - 使用 AVPlayer 在 Swift 中播放音频文件

转载 作者:搜寻专家 更新时间:2023-11-01 05:43:56 26 4
gpt4 key购买 nike

我有一个非常简单的方法,可以使用 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()

}

}

最佳答案

你为什么不试试“做”和“抓”呢?

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)
}

并放置 audioPlayer.play()在您想玩的功能上。

关于ios - 使用 AVPlayer 在 Swift 中播放音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39572859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com