How can I play compressed sound files in C# in a portable way?

前端 未结 9 1825
陌清茗
陌清茗 2020-12-14 02:43

Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short \"jingle\" sounds on various events occuring in the program.

9条回答
  •  孤街浪徒
    2020-12-14 03:24

    I neither want to distribute any binaries with my application nor depend on P/Invoke, as the project should run at least on Windows and Linux. I'm fine with bundling .Net assemblies as long as they are license-compatible with GPL.

    Unfortunatly its going to be impossible to avoid distributing binaries, or avoid P/Invoke. The .net class libraries use P/Invoke underneath anyway, the managed code has to communicate with the unmanage operating system API at some point, in order to do anything.

    Converting the OGG file to PCM should be possible in Managed code, but because there is no Native Support for Audio in .net, you really have 3 options:

    1. Call an external program to play the sound (as suggested earlier)

    2. P/Invoke a C module to play the sound

    3. P/Invoke the OS APIs to play the sound.

    (4.) If you're only running this code on windows you could probably just use DirectShow.

    P/Invoke can be used in a cross platform way http://www.mono-project.com/Interop_with_Native_Libraries#Library_Names

    Once you have your PCM data (using a OGG C Lib or Managed Code, something like this http://www.robburke.net/mle/mp3sharp/ of course there are licencing issues with MP3), you will need a way to play it, unfortunatly .net does not provide any direct assess to your sound card or methods to play streaming audio. You could convert the ogg files to PCM at startup, and then use System.Media.SoundPlayer, to play the wav files generated. The current method Microsoft suggests uses P/Invoke to access Sound playing API in the OS http://msdn.microsoft.com/en-us/library/ms229685.aspx

    A cross platform API to play PCM sound is OpenAL and you should be able to play (PCM) sound using the c# bindings for OpenAL at www.taoframework.com, you will unfortunatly need to copy a number of DLL and .so files with your application in order for it to work when distributed, but this is, as i've explained earlier unavoidable.

提交回复
热议问题