7

How can I play a sound file with AVFoundation in a Swift playground? Ideally, the file would be in a URL, not in the local drive, but that's not important.

cfischer
  • 24,452
  • 37
  • 131
  • 214
  • 1
    Any code you tried so far? – Maxim Shoustin Oct 30 '14 at 16:29
  • Look at this link http://stackoverflow.com/questions/24043904/creating-and-playing-a-sound-in-swift?rq=1 – Aniket Bochare Oct 30 '14 at 16:33
  • I'm not sure that you can. For sure you can create new folder `Resources` under `playground` content and further Playground will find it with path something like: playing file:///var/folders/74/d78g19sj65bc6z2n6gjw9n4r0000gn/T/com.apple.dt.Xcode.pg/applications/YourApp-67685-8.app/Want_You.mp3 but `avPlayer.prepareToPlay()` will always returns `false`. – Maxim Shoustin Oct 30 '14 at 17:05
  • Yes, I'm afraid it must be a bug in the playground implementation – cfischer Oct 31 '14 at 12:11

2 Answers2

2

I'm fumbling around in the dark on this one myself, but I think it may be due to some limitation of swift playgrounds. Consider this code:

#!/usr/bin/swift

import Cocoa
import AVFoundation

var error: NSError?

println("Hello, Audio!")
var url = NSURL(fileURLWithPath: "/Users/somebody/myfile.mid") // Change to a local midi file
var midi = AVMIDIPlayer(contentsOfURL: url, soundBankURL: nil, error: &error)
if midi == nil {
    if let e = error {
        println("AVMIDIPlayer failed: " + e.localizedDescription)
    }
}
midi.play(nil)
while midi.playing {
    // Spin (yeah, that's bad!)
}

If we run this swift script in the terminal, it works fine and plays the midi file, but if you run the code in a playground, you get

AVMIDIPlayer failed: The operation couldn’t be completed. (com.apple.coreaudio.avfaudio error -1.)

On the positive side, being able to run it in a terminal shows that the code does work.

Charphacy
  • 2,110
  • 1
  • 20
  • 12
1

This works on a project I haven't tried on Playground. First drag your sound to your project and choose to copy for your destination if needed and check "add to target" to your app.

import Cocoa
import AVFoundation


var beepSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("beep", ofType: "aif")!)
func initBeep(){
    beepPlayer = AVAudioPlayer(contentsOfURL: beepSound, error: nil)
    beepPlayer.prepareToPlay()
}

func playBeepSound(){
    beepPlayer.play()
}
func applicationDidFinishLaunching(aNotification: NSNotification?) { 

    initBeep() 
}
@IBAction func btnPlayBeepSound(sender: AnyObject) {
   playBeepSound()
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571