user1542897
user1542897

Reputation: 43

Easiest way to play SOUND with MONO on OSX

I am writing a simple timer app for OSX10.6 using Mono. How can I play an alarm sound (it may be a wav/mp3 file or something else)?

I tried several ways, unfortunately none did work:

  1. NSSound seems to be not supported by Mono yet.

    MonoMac.AppKit.NSSound alarm = new MonoMac.AppKit.NSSound("alarm.wav");
    alarm.Play();
    
  2. Using a SoundPlayer didn't work either:

    System.Media.SoundPlayer player = new System.Media.SoundPlayer("alarm.wav");
    player.PlaySync();
    
  3. I was able to play a sound by opening a System.Diagnostics.Process and then use the OSX command line command afplay. Unfortunately, this command opens in a new terminal window, which is quite annoying in a GUI app.

I realize there are CoreAudio bindings in Mono. But I have not figured out how to use them to play a sound.

Upvotes: 4

Views: 2513

Answers (1)

Kevin Montrose
Kevin Montrose

Reputation: 22601

You're using the wrong NSSound constructor is all.

new MonoMac.AppKit.NSSound("alarm.wav") expects an NSData (implicitly cast from string), you want to use new NSSound(string, bool). Probably want to pass false for the second parameter.

I threw together a quicky test project (based on the default MonoMac project) to confirm this works:

public override void FinishedLaunching (NSObject notification)
{
  mainWindowController = new MainWindowController ();
  mainWindowController.Window.MakeKeyAndOrderFront (this);

  // Only lines added
  var sound = new NSSound("/Users/kevinmontrose/Desktop/bear_growl_y.wav", byRef: false);

  sound.Play();
}

Upvotes: 2

Related Questions