Play Sound on Swift Playground

How can I play an audio file with AVFoundation in Swift playground ? Ideally, the file will be in the URL, not on the local drive, but that doesn't matter.

+5
source share
2 answers

I myself fiddled in the dark, but I think this may be due to some limitation of fast 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 bad!) } 

If you run this quick script in the terminal, it works fine and plays a MIDI file, but if you run the code on the playground, you will get

AVMIDIPlayer error: operation could not be completed. (error com.apple.coreaudio.avfaudio -1.)

On the plus side, the ability to run it in the terminal shows that the code really works.

+2
source

This is working on a project that I have not tried on the Playground. First, drag your sound into your project and, if necessary, select a copy for your destination and check "add to destination" in your application.

 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() } 
+1
source

Source: https://habr.com/ru/post/1205880/


All Articles