Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing a sound in a Swift Playground

Tags:

swift

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.

like image 818
cfischer Avatar asked Oct 30 '14 16:10

cfischer


People also ask

What is swift playground used for?

Swift Playgrounds is a revolutionary app for iPad that makes learning Swift interactive and fun. It requires no coding knowledge, so it's perfect for students just starting out.

What type of code does swift playground use?

But then what? Swift Playgrounds teaches concepts and uses real Swift structure, but it's not real code. It doesn't make an app, it just guides Byte around and solves puzzles. Swift doesn't have a real command called collectGem() after all.


2 Answers

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.

like image 60
Charphacy Avatar answered Nov 09 '22 23:11

Charphacy


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()
}
like image 37
Leo Dabus Avatar answered Nov 09 '22 22:11

Leo Dabus