Building your individual audio participant with .NET — half 1
As nice as .NET is for writing software program for a number of platforms, it lacks some vital capabilities. This applies to these functionalities that will work radically otherwise on totally different CPUs and working methods. One of those is the flexibility to play sound.
With its predecessor, the .NET Framework, you can play sound simply by utilizing courses like SoundPlayer from the usual class library of the framework itself. Likewise, NuGet packages resembling NAudio added many additional audio-processing capabilities.
Unfortunately, NAudio just isn’t totally suitable with the cross-platform capabilities of .NET. Although it makes use of the newest .NET model, it’s nonetheless primarily focused at Windows.
There is, after all, a dependable manner to play sound on .NET on any platform, nevertheless it requires fairly a number of further dependencies. You must set up ASP.NET Core elements even for those who don’t want any internet growth capabilities, and make it interoperate with Node.js, to get this resolution to work.
Therefore, if you would like to have the ability to play audio on .NET in probably the most environment friendly manner with out loading too many further elements, you possibly can write your individual library to take action. Fortunately, the method just isn’t prohibitively tough, as I’ll present you on this article.
In this submit, we are going to concentrate on methods to get the bottom library construction arrange and methods to play audio if it’s put in on Windows. In the next posts, we are going to introduce Linux and Mac OS compatibilities as properly.
Setting up the venture construction
We will need our code to be reusable in different .NET packages. Therefore, the venture kind that we’re constructing is a normal .NET class library.

Once the venture is created, we might want to set up it into an optimum construction for a library with audio playback capabilities. The very first thing we are going to do is create an interface with widespread audio participant strategies. As every working system has a distinct manner of taking part in audio, there will likely be one implementation of this interface per OS. Each of these courses will likely be inside, because the code that can use the library shouldn’t be involved with which implementation to make use of. This determination will likely be dealt with by the library itself.
The construction of our interface is as follows:
namespace InternetCoreAudio.Interfaces;
public interface IPlayer
{
Task Play(string fileName);
Task Pause();
Task Resume();
Task Stop();
}
Now, we will add the Windows-specific implementation of the interface.
Send instructions to MCI on Windows
To play audio on Windows, we might want to use winmm.dll, a local library from the OS, which kinds the core a part of Windows Multimedia API. The solely a part of this DLL that we’re occupied with is the strategy that may sends audio-specific instructions to the API. And, to make use of it, we have to hyperlink to the DLL from our code.
This is achieved by the DLLImport attribute, which permits us to create a way in our managed C# code that maps on to a way throughout the native DLL that we’re linking to. The technique we’re occupied with is mciSendString. And, to make use of it, we might want to have the next in our class that implements the IPlayer interface talked about beforehand:
[DllImport("winmm.dll")]
personal static extern lengthy mciSendString(string command, StringBuilder stringReturn, int returnLength, IntPtr hwndCallback);
The technique has a number of parameters that enable us to regulate the execution of instructions and obtain the callbacks. However, for demonstration functions, all instructions that we’ll ship to this technique will likely be in a easy “hearth and neglect” method. Therefore, apart from the command textual content itself, we are going to set all different parameters to nulls, zeroes, and null pointers. If you want one thing extra subtle, the detailed documentation is out there right here.
The technique that can obtain Windows Multimedia API instructions and execute them will likely be as follows:
personal void ExecuteMsiCommand(string commandString)
{
var outcome = mciSendString(commandString, null, 0, IntPtr.Zero);
if (outcome != 0)
{
throw new Exception($"Error executing MSI command. Error code: {outcome}");
}
}
The mciSendString technique invocation inside it returns 0 if the command has been executed efficiently. Any worth aside from zero is an error code. This is why we’re throwing an exception.
Now, on to the instructions that must be despatched to the strategy. The instructions outlined beneath are simply commonplace C# strings. Each of those instructions is case-insensitive. However, I’ve used some capital letters for readability.
First, let’s look at a possible implementation of the Play() technique of the IPlayer interface. In our instance, we are going to name the ExecuteMsiCommand() technique outlined earlier thrice.
We will likely be utilizing the identical audio system for all of our operations; due to this fact, earlier than we begin the playback, we might want to shut some other media being performed by the identical system. This will be achieved by sending the next command to ExecuteMsiCommand() perform:
Close All
After this, we might want to open a media system and provides it a reference to a file that we wish to play. It can even be given an alias that will likely be usable within the instructions executed afterward. “myDevice” will be any alias of your alternative. The “fileName” parameter both represents an absolute path to the audio file in Windows format (e.g. C:Tempaudio.mp3) or a path relative to the folder the place the applying resides.
Open {fileName} Type MPEGVideo Alias myDevice
We assume that an interpolated string is used to insert the fileName parameter into the command, therefore the curly brackets.
Next, we are going to play the file, which is finished as follows:
Play myDevice
Pause and resume instructions include the corresponding verb adopted by the system alias in order that it is going to be “Pause myDevice” and “Resume myDevice” respectively. For stopping the playback, both “Close” or “Stop” command can be utilized adopted by the system alias.
This documentation explains how the system alias works. this reference web page accommodates the complete checklist of the instructions that can be utilized.
The excellent news is that with the playback kind being set to MPEGVideo, the instructions despatched to the mciSendString technique can play MP3 and WAV codecs, in addition to some other format that can be utilized by MPEG movies.
Something to look out for
As I’ve been testing the library, I’ve found that the “Open” MCI command doesn’t work very properly underneath some eventualities; inside a multi-threaded utility is one in all them. In these instances, it would return an error code 266, which is generally returned when an accurate codec can’t be discovered on the system. When this occurs, the audio system is not going to be opened; due to this fact any try to execute some other command in opposition to the system alias will fail.
However, there’s a workaround for that. It is feasible to run most MCI instructions instantly in opposition to a file title as a substitute of an alias. So, if the “Open” command is throwing 266 and you’re pulling your hair looking for out why, you possibly can skip the command and use the next one to start out the playback:
Play {fileName}
One factor to notice although. the “Close” command doesn’t work with the file title. So, if there isn’t any system alias out there, you possibly can carry out the next command to cease the playback:
Stop {fileName}
And observe it up with this command:
Close All
Wrapping up
A code repository that makes use of the rules proven on this brief tutorial, InternetCoreAudio, is out there right here. It additionally has a console app that can be utilized to see the category library in motion.
This is it for half one. In the following article, I’ll reveal the Linux implementation of the IPlayer interface.
HI-FI News
through Software Engineering on Medium https://ift.tt/hLeZla5
December 7, 2023 at 02:15PM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT








