swiftcore-audioswift-playgroundavaudiofile

AVAudioFile in Swift Playground results in "error -54"


I decided to have a play with AVAudioPlayer in a Swift Playground. The following code works fine in a normal Swift project, but returns the following error when running it in a Playground (in the assistant editor):

2015-05-12 00:08:04.374 AVAudioFile[2481:141158] 00:08:04.374 ERROR: AVAudioFile.mm:266: AVAudioFileImpl: error -54

Here is the code:

import Cocoa
import AVFoundation

var audioFileURL = NSURL(fileURLWithPath: "/Users/scooby/Desktop/song.wav")
var error: NSError?
var audioFile = AVAudioFile(forReading: audioFileURL, error: &error)

Printing the error out comes with:

Error Domain=com.apple.coreaudio.avfaudio Code=-54 "The operation couldn’t be completed. (com.apple.coreaudio.avfaudio error -54.)" UserInfo=0x7fa8c0736f70 {failed call=ExtAudioFileOpenURL((CFURLRef)fileURL, &_extAudioFile)}

Just can't figure out why its only an error in a Playground. Any ideas at all?

Thanks!


Solution

  • Xcode 6

    1. Open the Playground in the Finder ("Show package contents")
    2. Create a "Resources" folder inside
    3. Add your file in the folder
    4. Quit and relaunch the Playground

    To use the file:

    let audioFileURL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "wav")
    var error: NSError?
    let audioFile = AVAudioFile(forReading: audioFileURL, error: &error)
    

    Xcode 7

    No need for a workaround anymore.

    Open the Playground's Project Navigator (CMD+1) then drag & drop your file(s) into the existing "Resources" folder.

    To use the file:

    do {
        if let audioFileURL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "wav") {
            let audioFile = try AVAudioFile(forReading: audioFileURL)
            // use audioFile here
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }