用AVAudioPlayer播放本地音频文件 [英] Play local audio file with AVAudioPlayer

查看:253
本文介绍了用AVAudioPlayer播放本地音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在下载文件并获取它的本地方式,如下所示:
文件:///用户/管理员/库/开发商/ CoreSimulator /设备/ 4CDF286B-543F-4137-B5E2-C312E19B992F /数据/集装箱/数据/应用/ E5F13797-A6A8-48A1-B3C3-FBC3D7A03151 /文档/ 4d13e04980d3。 mp3



现在我想用AVAudioPlayer播放这个文件,但是我总是收到这个错误:

  file:/// 
错误域= NSOSStatusErrorDomain代码= 2003334207(null)
$ b

播放代码:

  var alertSound = NSURL(fileURLWithPath: 文件:///用户/管理员/库/开发商/ CoreSimulator /设备/ 4CDF286B-543F-4137-B5E2-C312E19B992F /数据/集装箱/数据/应用/ E5F13797-A6A8-48A1-B3C3-FBC3D7A03151 /文档/ 4d13e04980d3。 mp3)
print(alertSound)

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

我应该如何使用它?

$ b $在iOS8下,您保存的路径在启动时无效。您看到的IDE5F13797-A6A8-48A1-B3C3-FBC3D7A03151将随每次启动而改变。
$ b

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


I'm testing my app in simulator.

I'm downloading file and getting it's local way like this one: file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3

Now I want to play this file with AVAudioPlayer but I'm always getting this error:

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

Code for playing:

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

How should I make it playing?

解决方案

Under iOS8, the path that you have saved won't be valid across launches. The id you see "E5F13797-A6A8-48A1-B3C3-FBC3D7A03151" will change with each launch.

The solution is to save the filename and not the complete path, and to recreate the URL or complete path, by getting the path to the Documents (or tmp) folder and appending the filename to it.

这篇关于用AVAudioPlayer播放本地音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆