I've done a bit of Swift and a fair amount of Objective-C on iOS, but basically no real OS X programming, so I haven't used NSSound
. I was trying to help someone on a Swift forum, and ... it's not working. I'm not sure why.
In a playground, Swift REPL or even a script (#!/usr/bin/env swift
), I can instantiate an NSSound successfully:
NSSound(named:"Hero")
In REPL / Playground or printing from the script, I can see that the optional has an NSSound inside. But when I call play()
, I don't hear anything:
NSSound(named:"Hero")!.play()
Why?
This is a very small piece of code, it seems pretty simple, but obviously I'm missing something. It's not a big deal because it's not code that I need, but it's bugging me because it seems so simple and yet it's not working.
NSSound plays its sound asynchronously. By default, a playground exits immediately after executing the its code, so the process terminates before the sound has had a chance to play.
Here's a quick and dirty way to keep the playground alive indefinitely so that you can hear the sound play.