如何访问斯威夫特应用程序的声音文件 [英] How to access sound files in Swift app

查看:113
本文介绍了如何访问斯威夫特应用程序的声音文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建一个iPhone应用程序下载斯威夫特的声音文件,我有一个问题。利用X code和iOS的模拟器,我能够成功下载,我需要到模拟器的音频文件。我发现,正在下载的文件都在这个目录中我的OSX的机器上:

So I am creating an iPhone app that downloads sound files in Swift and I had a question. Using Xcode and the iOS simulator, I'm able to successfully download the audio files that I need onto the simulator. I found that the files being downloaded are in this directory on my OSx machine:

OS X - >用户 - >我的名字 - >图书馆 - >开发 - > CoreSimulator - >设备 - > 96CDD ... - >数据 - > 6B742 ... - >文件

OS X -> Users -> "My name" -> Library -> Developer -> CoreSimulator -> Devices -> 96CDD... -> data -> 6B742... -> Documents

现在我的问题是这样的,我知道我有应用程序内的设备上的音频文件,但我如何访问它们,然后从应用程序本身打他们?我想只使用AVAudioPlayer,但我已经在访问文件失败。这里是code我试图运行的是viewDidLoad中函数中:

Now my question is this, I know I have the audio files on the device inside of the app, but how do I access them and then play them from the app itself? I'm trying to just use AVAudioPlayer, but I've been unsuccessful in accessing the file. Here is the code I'm trying to run which is inside of the viewDidLoad function:

    var playYoda = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Documents/do_or_do_not", ofType: "wav")!)
    println(playYoda)

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)

    var error:NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: playYoda, error: &error)
    audioPlayer.prepareToPlay()
    audioPlayer.play()

我所有的code编译的,但是当我启动模拟器,我得到这个错误:致命错误:意外地发现零,同时展开一个可选值就在第一线code,我联系(VAR playYoda = ...)。

All of my code compiles, but when I start the simulator, I'm getting this error: fatal error: unexpectedly found nil while unwrapping an Optional value right at the first line of code that I linked (var playYoda = ...).

我不知道这是否是因为我的道路是错误的音频文件,或者如果我做错事与AVAudioPlayer。任何帮助将是AP preciated。

I don't know whether this is because my path is wrong to the audio file, or if I'm doing something wrong with AVAudioPlayer. Any help would be appreciated.

推荐答案

如何是这样的:

let fileManager = NSFileManager.defaultManager()

let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

if let documentDirectoryURL: NSURL = urls.first as? NSURL {
    let playYoda = documentDirectoryURL.URLByAppendingPathComponent("do_or_do_not.wav")

    println("playYoda is \(playYoda)")
}

这篇关于如何访问斯威夫特应用程序的声音文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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