Posted in:

I mentioned in my post about concatenating audio in NAudio that I have wanted to introduce a fluent API into NAudio for many years, but have yet to get round to it.

The “pipeline” nature of audio applications lends itself very well to a fluent API. In much the same way you can chain together LINQ extension methods, with NAudio you connect together IWaveProvider or ISampleProvider objects to construct a signal chain.

The good news is that I’ve already made a start. On top of the existing extension methods ToSampleProvider, ToWaveProvider and ToWaveProvider16, which existed to help you move seamlessly between IWaveProvider and ISampleProvider components, I’ve added several more to make building a signal chain easier.

Skip and Take allow you to jump over a portion of time, and read up to a predefined timespan from a source ISampleProvider. So for example if you wanted to extract a 30 second clip from an MP3 file, starting 1 minute in you could do it like this:

var source = new Mp3FileReader("file.mp3")
                    .ToSampleProvider()
                    .Skip(TimeSpan.FromMinutes(1))
                    .Take(TimeSpan.FromSeconds(30));

Obviously this idea could be taken a lot further. I’ve already added FollowedBy for concatenating ISampleProvider components, as well as ToMono and ToStereo. But I have loads of ideas for additional extension methods to simplify things like resampling, looping, mixing, passing through effects, and writing to files.

There are some challenges to this approach. Adding components that need real-time control such as changing volume or equalizer settings, or repositioning in a file will require passing in some kind of observable control object, and I’ve still not decided what the best way to ensure that disposable components in the signal chain can get disposed when you are finished playing.

But anyway, if you get the latest source code from GitHub you can have a play. The new methods will be part of the next release of NAudio, hopefully in the not too distant future.

Want to get up to speed with the the fundamentals principles of digital audio and how to got about writing audio applications with NAudio? Be sure to check out my Pluralsight courses, Digital Audio Fundamentals, and Audio Programming with NAudio.