Introduction

Many times I have seen people asking in the forums for sound support for .NET. Unfortunately, we had to make do with difficult unmanaged dll's or use the media player interface. Then one day I came along a "little" sound library called BASS. This is a sound library that provides you with various static functions for playing, creating, streaming and recording sound. It has support for WAV/MP3/MP2/MP1/OGG sound formats as well a variety of popular MOD formats. With the addition of their WMA addon, the library supports WMA playback as well as WMA creation and network streaming. Having a VB.NET API on the BASS website, I used that as my starting point. NOTE: You must download the BASS and BASSWMA package from the BASS website and copy the 2 dll's to the application folder.

Design

One of the big problems with consuming unmanaged code is the fact that you do not deal directly with objects, but rather with handles to undefined objects. But more on that later. Like I said my starting point was the VB.NET "API". All it is really is a mapping to all the functions provided by the BASS dll. Still that was too unfriendly for me. I then started rewriting all the functions over to C#, and adding more meaningful functions to be used from within .NET. In the code you will notice all unmanaged calls start with an underscore (_) and they usually will have a "friendly" public counterpart.

After remapping all the functions, I started working on the class hierarchy. Several options down the line, I finally came up with a solution that would work. This was essential as several of the static functions can be preformed on a variety of objects (handles). Basically, I created a base class (ChannelBase) and let my defined objects inherit from there or from an object already inheriting from ChannelBase. In some cases like Stream and Music, I created an intermediate abstract class (AdvancedChannel) from which they inherited. All in all, the structure works very well and saves a lot on duplicate code. Unfortunately, when consuming unmanaged dll's there always seems to be a fair amount of duplicate code (obviously having the source to BASS would have simplified things, but I am not that lucky).

Having the structure in place, I started designing my own classes for managed use. Basically, I went by wrapping a class around a handle and "hiding" the handle from the user and let him/her rather work with an object directly. On object creation, a handle would be passed to the constructor and the resulting object would be returned. I opted not to have public constructors for my objects as most need to have BASS initialized first. So once a BASS class was created, further objects can be created from there, with the exception of the CD and Record class. They are allowed to be instantiated with public constructors.

Having objects (with handles) made it possible for me to rewrite all unmanaged functions from:

staticint UnmanFunc(IntPtr handle, int someparam);

to

void ManFunc(int someparam);

All "freeing" functions from BASS dll has also been implemented into their respective finalizers, so the implementer does not have to worry about freeing up unmanaged resources. I didn't go for the IDisposable model as it seemed to create more "work" than that is supposed to prevent. UPDATE: IDisposable has been implemented.

An exception model was also implemented, by using the static GetErrorCode() function provided. In other words, the user does not check for an error, but rather wait for an exception.

An event model was also implemented for when the "sound" stops playing. The marshalling required for this was quite tricky. You can have a look inside AdvancedChannel.

Finally, it came round to testing all the functions provided by the BASS dll. There were some really "weird" (from a C# perspective anyways) marshalling to be done to get the functions to behave like they should. I had to implement some classes to solve some problems, for example the ChannelAttributes class. This is really only a "placeholder" for some variables , making life alot easier when having to modify some settings. You can also have a look at the FX class to see how I handled the void * type from my code.

Testing

I have created various test projects to test various functions. Here are some screenshots:

Please note: The BASS dll requires a valid window handle to function, so either pass IntPtr.Zero (foreground window) or the form's handle.

Documentation

I have tried to do as much as possible for documentation, but it still lacks huge parts. I have included an nDoc generated help file with most of the documentation coming straight from the BASS dll's docs. I have tried to keep the functions as closely related to their static unmanaged counterparts.

I have since first public release also included a changelog as the project is still under heavy development, but mostly functional.

Conclusion

Playing sounds from within C# cant be easier than this. If you have any comments, suggestions, remarks, please feel free to contact me. This was my first project of such a kind, but I believe it was successful.

Updates

nBASS 0.9.5 (9 September 2002)

- Fixed bug in WMAStream.GetTags()- Added IDisposable to classes (big thanks to Joel Mueller)- ChannelBase and AdvancedChannel is now abstract (again, thanx to Joel)- Change exceptions to show message when exception is thrown without having to do it manually

file: BASS.CS
line: if (_Init( device, freq, (int) flags, hwnd) == 0) throw new BASSException();
error: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

"I'm new to programming audio and video. I've downloaded the nBASS project but i'm unable to get it executed on my system please resolve the issue of missing DLL reference to file base.dll the exception trace is given below. System.DllNotFoundException was unhandled Message="Unable to load DLL 'bass.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)" Source="nBASS" TypeName="" StackTrace: at nBASS.BASS._GetVersion() at nBASS.BASS.get_Version() at nBASS.BASS..ctor(Int32 device, Int32 freq, DeviceSetupFlags flags, IntPtr hwnd) at ModTest.Form1..ctor() at ModTest.Form1.Main() at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()"
- t_anvesh

Using VS2005, I get the above message when I try to run the SteamTest example (or any of the test code for that matter).

I downloaded the BASS and BASSWMA packages and coped bass.dll (tried both v2.3 and v1.8) and basswma.dll into my VS2005 application folder to no avail. As I flailed about trying to get this to work I also put copies of the two DLLs in the following folders:
...\nBASS-0.9.6.1\
...\nBASS-0.9.6.1\StreamTest\
...\nBASS-0.9.6.1\bin\

Also, I get a dialog box stating that the module being executed "... was built wither with optimizations enabled or withput debug information...". Anyone have any idea what the source of this problem is?

Hi Sir,
How can i do a sound record from the line-in sound card input using nbass ?
i found all kind of examples in ur downloadable source code except sound record example , please if u can , i wanna know how do it , if u have an example too , i will be appreciating ur help
u can send it to my mail or post it here
thanks in advance

I have a problem when i try to use this dll.
On this row: bass = new BASS(-1, 44100,DeviceSetupFlags.Default, this.Handle); i always get thsi exception:An unhandled exception of type 'System.DllNotFoundException' occurred in nbass.dll

Any chance of updating nBass to work with BASS 2.2? A number of functions have changed since your code was written. I could help with some things, but I don't have time to do everything or especially to test everything.

I can't play a sound with this library! It loads fine, but no sounds are played, EVER. There's no sound, and I can't get the Position or Length to show either. I've pretty much copied the sample code from the stream sample, but I still can't get sounds to play. I would show the code that I'm using, but it is very long. leppie, do you think there is any chance that you could take a look at the code for me and tell me what I am doing wrong?

By the way, I'm using the latest version of the nBASS library, the latest version of the .NET Framework, and VS.NET 2002, C#.

now to my question. I want to control the volume of two streams independent of each, but if i set the stream.Attributes.volume, nothing happens.
And if i control the bass.StreamVolume, this sets the streamvolume of all bass instances.

Is there a way to control the volume of several streams independent to each other ?
This one is for mixing up music with controlled volume progress.

I was just finishing a little test with the VB.NET API and I must tell you it was not fun.

what you did, was what the authors of the bass api should have done in the first place...

what my app needs to do, and I'm still figuring that out, is to write different .wav samples in different location in the target file (the app is a little midi drum machine, with wave samples, and I would like to have an option to render the output to a wave file)
I'm sure that its possible, all I'm lacking is to know how to create a file output stream and to control what to write to it and when (like how to write silence, just put a 0 byte?? ) as you can see I have no knowledge of wave file format... so any help will be VERY appreciated

I've tried to work with the original documentation but it was not helpful at all (to me)

I also have the problem. When I entered www.un4seen.com and found no entry to get older bass.dll such as version 1.7. So could mail it to me when anyone find it Or tell me the nBass could run with lastest bass.dll?
Email: wdz163ren@163.com
Thanks a lot!

Now, I found out, that if I change
bass1 = new BASS(-1 , 44100, DeviceSetupFlags.Default, new IntPtr(0));
to
bass1 = new BASS(0, 44100, 0, this.Handle);
the Error "Illegal Device Number" is gone and there came a new one:
"The requested data is not available".
I think, he can't find the Stream/File?!

Now, I found out, that if I change
bass1 = new BASS(-1 , 44100, DeviceSetupFlags.Default, new IntPtr(0));
to
bass1 = new BASS(0, 44100, 0, this.Handle);
the Error "Illegal Device Number" is gone and there came a new one:
"The requested data is not available".
I think, he can't find the Stream/File?!

when a song ends, what event is passed, from the stream, or the bass object, as i want my program to go straight into playing another song in a playlist as soon as the end of song event is triggered( if there is such an event)

i have a visualisation up and running , using your code as an example as the help file is very bare. can you give me more info on the channel data flags that i use, eg SFFT2048. i see there are a few of theese flags but the difference each one is beyond me. also , i got the trackbar to move using your code as an example, but i also dont understand the process fully. can you expand on this at all for me??

I would like to write a telephone programm and I need to encode recorded data immediately. My problem is that, as I see, a WMAencoder object can
only encode to a file on disk, given by a string-filename.
Is it - somehow - possible to encode to a Stream(.net object) instead
of a file?

I don't care about 20msec delay. I would be happy, with 100msec delay!
I would like to record e.g 80 msec wav, encode it and send it.
(I want data travell in xml in a HTTP request to be able to work
via firewalls. Dataspeed (3000byte/sec) and everything is calculated,
I only need a mp3/wma (.net)encoder )
I looked after other dll-s (lame_enc, and mpglib/mpg123), but I'm not
sure I would be able to write a .net wrapper for them. They look
complicated for me

hi. im quite stuck trying to implement nBass.
i go to add a reference, select the nBass.dll, add it, but when i run the programme i am told that the bass dll cannot be found so i tried to add the bass.dll and i am told its not a dll or a COM object and it cant be used. when i create a bass object in c#, it all comes up fine when i tipe BASS bass = new bass(paremeters), but it just wont run. any ideas of what to do?thank you...this happens in my programme and the example that i got with nBASS
fintan guihen

by reference i mean to add it to the c# project so that i can call upon it. its opk, i sorted it , im not sure how but its working now. something to do with the window. i got the latest version 2.0 of bass just yesterday . thank you kindly for replying