小编典典

使用AVAudioPlayer播放本地音频文件

swift

我正在模拟器中测试我的应用。

我正在下载文件,并以这种方式获取本地文件:
file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3

现在,我想使用AVAudioPlayer播放此文件,但是我总是遇到此错误:

file:///
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"

播放代码:

var alertSound = NSURL(fileURLWithPath: "file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3")
        print(alertSound)

        var error:NSError?
        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print(error)
        }

我应该如何播放?


阅读 337

收藏
2020-07-07

共1个答案

小编典典

在iOS8下,您保存的路径在启动期间将无效。您看到的ID“ E5F13797-A6A8-48A1-B3C3-FBC3D7A03151”将随每次启动而更改。

解决方案是保存文件名而不是完整路径,并通过获取Documents(或tmp)文件夹的路径并将文件名附加到该路径来重新创建URL或完整路径。

2020-07-07