Search code examples
c#audiovisual-studio-2017visual-studio-macsoundplayer

SoundPlayer on Visual Studio 2017 Mac outputs no sound


I have instantiated a System.Media.SoundPlayer and I am (trying to) use it to play a .wav file. However, as you may have picked up from the title of this, it isn't working (no sound is being outputted). I am using C# and creating a Console application in Visual Studio 2017 Mac. Here is my code:

using System;
using System.Threading;
using System.IO; // Not needed yet
using System.Media;

namespace mathsTestConsoleC
{
    public class OutputClass
    {    
        public void PlayMusic()
        {
        SoundPlayer player = new SoundPlayer
        {
            SoundLocation = @"/Users/felix/Projects/mathsTestConsoleC/mathsTestConsoleC/backgroundMusic.wav"
        };

        player.Load();
        player.Play();
        }
    }
}

(I realise that you don't necessarily need to use player.Load(); because the player.Play(); includes that.)

This doesn't work either:

        public void PlayMusic()
        {
            SoundPlayer player = new SoundPlayer
            {
                SoundLocation = "/Users/felix/Projects/mathsTestConsoleC/mathsTestConsoleC/backgroundMusic.wav"
            };

            player.Load();

            Thread.Sleep(500);

            if (player.IsLoadCompleted == true)
            {
                player.Play();
            }

            else if (player.IsLoadCompleted == false)
            {
                Console.WriteLine("player.IsLoadCompleted == false");
            }

            else 
            {
                Console.WriteLine("player.IsLoadCompleted == not set");
            }

        }

When I call PlayMusic(), my application doesn't play the .wav file that I have given it.

I hope you can help!


Solution

  • Mono substitutes the Windows-specific with calls to the ALSA (Advanced Linux Sound Architecture) specific libasound.so library.

    Re: http://www.alsa-project.org/main/index.php/Main_Page

    The easy way to play audio from a console app on the Mac is to shell a process and run afplay:

    afplay
    
        Audio File Play
        Version: 2.0
        Copyright 2003-2013, Apple Inc. All Rights Reserved.
        Specify -h (-help) for command options
    
    Usage:
    afplay [option...] audio_file
    

    Otherwise you can create a Xamarin.Mac-based app and you would have full access to the audio system so you could use NSSound or the CoreAudio framework.