Click here to Skip to main content
Click here to Skip to main content

C# MP3 Sound Capturing/Recording Component

By , 20 Oct 2009
 
Mp3 Capture Sample Application

Introduction

It's surprising that there are no components for sound capturing in .NET Framework 3.5. Even designers of WPF and Silverlight 2.0 were focused on graphics so deeply, that they forgot about applications recording sound from user's microphone. It is said that the next version of Silverlight will provide such functionality.

However, what you often want to achieve is to store the recorded sound in MP3 file (or send it as MP3 stream). That's legally complicated due to MP3 patent constraints. And for the same legal reason, we can assume that we will not see MP3 functionality in Microsoft technologies soon (there is WMA instead).

Here you find an easy to use .NET 3.5 component, providing Sound Capturing functionality for a Windows application. It outputs data as raw PCM samples or a regular WAV file. Or you can just set one boolean property to use LAME DLL and perform MP3 compression on the fly.

This article uses a subset of C# MP3 Compressor libraries written by Idael Cardoso which in turn are partially based on A low level audio player in C# by Ianier Munoz. See this website for technical and copyright information regarding the LAME project.

Background

I chose Managed DirectX (MDX) 1.1 to capture sound. The MDX project is currently frozen since Microsoft moved to XNA Game Studio Express (a solution rather inadequate just for capturing bits of sound). MDX is descended by SlimDX Open Source project which exposes roughly similar interfaces and delegates to the native DirectSound libraries.

MDX comprises of .NET assemblies delegating calls to native DirectX DLLs of 2006. We expect DirectX in a version backward compatible with the 2006 interfaces to be installed on virtually every Windows computer (yes, also works on Vista).

The component captures sound via MDX from a sound card in raw PCM format. PCM format is a simple sequence of sound sample values. The samples can be 8bit (0..255) or 16bit (-32768..32767) each. Stereo sound is a sequence of pairs of samples (left, right, left, right...). PCM is a proper format for streaming of raw data. Streaming means passing data in small chunks while the total volume of the data may be unknown. Raw PCM is the most basic type of output of Mp3SoundCapture component. If you direct stream this format to a WAV file, you will not be able to play it as WAV file must additionally contain a RIFF header.

WAV (RIFF) format requires the raw PCM data to be prefixed with RIFF header, which apart from format information also contains information about the total length of the PCM data in the file. That's why you can't really stream RIFF data, as the total size of the stream is usually unknown. WAV (RIFF) format is the second type of output of the Mp3SoundCapture component. You can direct stream this format to a WAV file.

The third type of Mp3SoundCapture component output is MP3. A Bit rate (kbit/s) is a parameter which decides MP3 sound quality. Apart from that, the sound quality depends on the format of PCM data being compressed. Not every combination of the bit rate and sampling parameters is allowed. You can usher MP3 stream to an MP3 file.

Using the Code

Setting Up

From your application, add a reference to Istrib.Sound.Mp3.dll assembly (see Istrib.Sound.Example.WinForms for example). MP3 compression also requires lame_enc.dll library to be located in binaries directory. Istrib.Sound.Mp3.dll assembly references Managed DirectX assemblies (located in DirectX subdirectory). The DirectX assemblies can be also installed in GAC via DirectX End-User Runtimes redistributable available for download at Microsoft site (here: Nov 2008 version).

If you experience "Loader Lock" warning while debugging your application, refer here for a workaround.

Istrib.Sound.Mp3.dll assembly contains a single component: Mp3SoundCapture. You may think of this component as of a sound recorder. You set up its properties prior to calling Start(...) and Stop() methods ("recorder buttons"). You provide a writable stream or a file path to each call to the Start method. Single instance of the component may capture sound many times to many streams/files one by one.

Component Construction

You may use Visual Studio Component Designer to drag and drop the Mp3SoundCapture component from the Visual Studio toolbox to the component surface or create the component manually:

mp3SoundCapture = new Mp3SoundCapture();

The component is ready to use just after construction. The default output is MP3 128kbit/s sampled at 22kHz, 16bit, mono. You specify sampling parameters and output format by setting the component properties.

Capturing Device (e.g. A Microphone)

You may use a default Windows recording device:

mp3SoundCapture.CaptureDevice = SoundCaptureDevice.Default;

Or choose one of the installed system sound capture devices:

mp3SoundCapture.CaptureDevice = SoundCaptureDevice.AllAvailable.First();

Output Format

You set one of the 3 output types:

  • Mp3SoundCapture.Outputs.Mp3 - MP3 format
  • Mp3SoundCapture.Outputs.RawPcm - Raw sample data (without a RIFF header)
  • Mp3SoundCapture.Outputs.Wav - WAV file data (including the RIFF header)
mp3SoundCapture.OutputType = Mp3SoundCapture.Outputs.Mp3;

Sampling Parameters

For PCM or WAV output, you may select any available sampling parameters supported by the sound card (PcmSoundFormat.StandardFormats):

mp3SoundCapture.WaveFormat = PcmSoundFormat.StandardFormats.First();

... or if you wish to hardcode it:

mp3SoundCapture.WaveFormat = PcmSoundFormat.Pcm22kHz16bitMono;

Sampling parameters for MP3 format are restricted to values returned by Mp3SoundFormat.AllSourceFormats. Not every combination of the sampling parameters and bit rate is allowed. If you choose the bit rate prior to sampling parameters, then you may use  Mp3BitRate.CompatibleSourceFormats property to list compatible values.

mp3SoundCapture.WaveFormat = myMp3BitRate.CompatibleSourceFormats.First();
//Or: mp3SoundCapture.WaveFormat = Mp3SoundFormat.AllSourceFormats.First();

MP3 Bit Rate

For MP3 output format, you specify one of the available bit rates. Again - you cannot pair each bit rate with each sampling parameters. If you choose sampling parameters prior to bit rate, then you may use PcmSoundFormat.GetCompatibleMp3BitRates() extension method to enumerate through compatible MP3 bit rates.

mp3SoundCapture.Mp3BitRate = myPcmSoundFormat.GetCompatibleMp3BitRates().First();
//Or mp3SoundCapture.Mp3BitRate = Mp3BitRate.AllValues.First();

... or if you wish to hardcode it:

mp3SoundCapture.Mp3BitRate = Mp3BitRate.BitRate128;

Volume Normalization Option

Often when an application records and stores many pieces of sound, it is required to adjust their volume so that all of them were at similar volume level. The Mp3SoundCapture has the NormalizeVolume property at your disposal to perform this transformation for you. Setting true causes all recorded sound pieces to be normalized, i.e. volume of the most loud section of the piece will be turned up to the highest possible level and all other sections will be turned up proportionally.

mp3SoundCapture.NormalizeVolume = true;

Note that the normalization algorithm must read the whole stream to find the loudest place, then rewrite the whole stream adjusting the volume of each sample. It means that the entire stream must be buffered before it is directed to the output. Mp3SoundCapture uses a temporary file to buffer the data when normalizing. MP3 compression, if applied, is done after the normalization. When you have recorded a sizeable piece of sound, the gross of processing takes place after calling Stop() met method, not on the fly (as it is when NormalizeVolume is false). It may take time. Here Mp3SoundCapture offers an asynchronous stopping.

Capturing

To start capturing, just call Start(Stream) method passing an open, writable stream (you must close it yourself after capturing has stopped - not obvious when using asynchronous stopping). You may also call Start(string) method passing an output file name.

To stop capturing, just call the Stop() method.

Asynchronous Stop()

As mentioned above, when normalizing, it may take some time after calling Stop() before all captured data is written to the output stream. Mp3SoundCapture has an option of immediately leaving Capturing state and passing all buffer processing to a separate thread. You can start the next recording session not waiting for the last bytes of data from the previous one. By default, the asynchronous behavior is disabled. To enable it, set:

mp3SoundCapture.WaitOnStop = false;

Note that you cannot close your output buffer passed to Start(Stream) method until a Mp3SoundCapture.Stopped event is fired. Use Stopped event arguments to get the reference to the stream which is ready for closing or - if you used Start(string filePath) - a path of the file which has just been closed by Mp3SoundCapture:

private void mp3SoundCapture_Stopped(object sender, Mp3SoundCapture.StoppedEventArgs e)
{
    //Now the e.OutputFileName file is ready and contains all captured data
    dataAvailableLbl.Text = "Data available in " + e.OutputFileName;
    dataAvailableLbl.Visible = true;
}

Points of Interest

In some development environment configurations, you may get "Loader Lock" error (which is really a warning) while starting your application under the debugger. It's a well-known design issue in Managed DirectX. You may disable this error in Visual Studio debugger settings (most people do this without observable consequences). I preferred not to do this. Instead I found a workaround: if the project which references Istrib.Sound.Mp3.dll also explicitly references Managed DirectX assemblies (Microsoft.DirectX and Microsoft.DirectX.DirectSound), then the warning is not raised. Otherwise the warning is shown by the debugger each time any assembly referencing Managed DirectX libraries is loaded into the Application Domain.

However - what I experienced - you cannot use Visual Studio Add Reference... wizard to add the DirectX GAC assembly reference. That's not an issue when you reference a local copy of DirectX assemblies (like in the example: DirectX subdirectory).

The workaround for the GAC problem is to add the reference to GAC assemblies manually editing your csproj file with a text editor:

<ItemGroup>
    ...
    <Reference Include="Microsoft.DirectX">
      <Name>Microsoft.DirectX</Name>
    </Reference>
    <Reference Include="Microsoft.DirectX.DirectSound">

      <Name>Microsoft.DirectX.DirectSound</Name>
    </Reference>
    ...
</ItemGroup>

Visual Studio Add Reference... wizard generates identical XML except it includes full assembly version info. This should work as well... but it does not, at least on my machines.

History

  • 29th November, 2008: Initial post
  • 1st December, 2008: More MP3 formats available
  • 19th October, 2009: Updated source code and demo project

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Lukasz Kwiecinski, Istrib
StaffPlan, Istrib
Poland Poland
Member
I am a .NET developer, working currently in the UK, though still strongly associated with Poland. Primary interests: business application, server-side, enterprise-scale solutions, SOA, thin but rich internet clients (Silverlight).
Apart from my everyday work, I spend a lot of time validating design patterns for newer technologies (like Silverlight, WCF, LINQ). My warzone is www.nauka-slowek.org - a proof of concept for asynchrony, internet multimedia and command pattern in client-server apps. I also use that website myself as it is a great tool to effectively learn vocabulary (foreign languages), which aids my long being abroad.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Suggestionthanksmembersmtpserver.in7 Nov '12 - 21:48 
you rocks
QuestionCapture system sound output with WasapiLoopbackCapturememberParDHarD8 Aug '12 - 3:37 
Check out this thread for a WasapiLoopbackCapture class that takes the output from your soundcard and turns it into a wavein device you can record or whatever...
 
https://naudio.codeplex.com/discussions/203605/
QuestionSending Output Over NetworkmemberMember 860113516 Jul '12 - 17:00 
Is there a way to put this into a memorystream rather than saving it so I can eventually stream it over my network And would any other changes be needed to stream it live rather than saving it?
AnswerRe: Sending Output Over NetworkmemberBrickCP25 Oct '12 - 17:13 
instead of starting the capture using a filename, use this:
 
Stream SWIn = new MemoryStream();
mp3SoundCapture.Start(SWIn);
 
then, on mp3SoundCapture_Stopped, do this:
 
e.OutputStream.Position = 0;
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(e.OutputStream.Length);
e.OutputStream.Read(storeStream.GetBuffer(), 0, (int)e.OutputStream.Length);
storeStream.Flush();
e.OutputStream.Close();
SaveMemoryStream(storeStream, @"C:\temp\tmp.enc");
storeStream.Close();
 
That is to save the stream. Useful if you want to encrypt it before it gets saved to a file.
 
It can then later be decoded into an mp3 and played.
 
To play the stream, have a look around, there are plenty of ways I've seen.
GeneralMy vote of 5memberFarhan Ghumra6 Jun '12 - 20:49 
superb
QuestionVery helpful, thank you very much!memberMember 87706558 May '12 - 21:20 
Works great and well written
GeneralMy vote of 1memberMember 850567226 Mar '12 - 0:28 
/
GeneralMy vote of 5memberFlavioAR25 Dec '11 - 12:30 
Modelo bastante completo para captura de �udio.
Excelente trabalho.
Parab�ns!!
QuestionSystem.BadImageFormatException was unhandled. Please HELP!!memberEl pulpo6 Dec '11 - 17:04 
Hello. I'm getting an System.BadImageFormatException was unhandled
Message=" is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)"
 
from a method inside the Istrib dll, in the Mp3SoundCapture.cs when I call the method
public void Start(string outputFilePath)
{
Start(new FileStream(outputFilePath, FileMode.Create, FileAccess.Write), true);
}
Can any body help me with this. Thanks
AnswerRe: System.BadImageFormatException was unhandled. Please HELP!!memberVirgil Reboton10 Feb '12 - 13:04 
Have you manage to make this sample work? I am having the same issue as you are. thanks.
I'm not crazy, I'm just a little unwell.

GeneralRe: System.BadImageFormatException was unhandled. Please HELP!!membercybspi@cu19 Feb '12 - 7:53 
make a new x86 configuration....all cpu will not work for this.
QuestionPause / Unpause supportmemberFederico Colombo17 Oct '11 - 11:51 
Excellent article, thank you !
 
Added Pause/Unpause support by adding this to Mp3SoundCapture class:
 
public void Pause()
{
    lock (CaptureLock)
    {
        if (capturing != null)
        {
            capturing.Process.Stop();
        }
    }
}
 
public void Unpause()
{
    lock (CaptureLock)
    {
        if (capturing != null)
        {
            capturing.Process.Start();
        }
    }
}

AnswerRe: Pause / Unpause supportmemberMember 79482867 Nov '12 - 12:06 
Can you give a better explanation of how you got Pause to work? I added your code and a Pause button to the main form as follows:
private void PauseBtn_Click(object sender, EventArgs e)
{
    if (PauseBtn.Text == "Pause")
    {
        mp3SoundCapture.Pause();
        PauseBtn.Text = "Resume";
    }
    if (PauseBtn.Text == "Resume")
    {
        mp3SoundCapture.Unpause();
        PauseBtn.Text = "Pause";
    }
}
 

But it is not working.
 
Thanks
QuestionTemp file sizememberGeorgeVL23 Sep '11 - 7:05 
Hi there,
 
great work to start with Smile | :)
 
Question: If I was to leave it recording at 44Khz 16bit stereo I expect the temp file size to grow over 2G in about 4 hours. Any ideas of how to go about breaking the output in multiple files?
 
Thanks
 
George
AnswerRe: Temp file sizememberGeorgeVL24 Sep '11 - 5:37 
Stand corrected, the application will continue writing past the 2Gb file size. Ignore the question
QuestionNot working in i7 processormemberJayawant Karale19 Aug '11 - 19:15 
Hi I am using your code it works nicely on every machine but it failed to work on i7 machine.
It is not able to record mp3 file.
Please help me
AnswerRe: Not working in i7 processormembermikeyii19 Sep '11 - 22:39 
Me too! Which error did you get?
GeneralRe: Not working in i7 processormembermikeyii20 Sep '11 - 2:53 
My solution was to compile the project as x86 binary, so that .NET-Framework can load the vlc DLLs.
Questionurgent! need helpmemberMember 795584911 Aug '11 - 22:57 
great code mr Lukasz. but since I am a newbie in audio programming I got a lot of confusion,
maybe, there are someone who want to help me, to tell me the minimum code to only capture the audio from microphone, and write it in maybe byte[] or stream from Mr. Lukasz project. Big thanks for everyone who help me
GeneralRe: urgent! need helpmemberojojoMA12 Aug '11 - 12:46 
This is exactly what i am searching for, too. I late want to visualize the FFT, but I am new to multimedia with C#, so I need something basic to start
Regards
GeneralMy vote of 5memberrrossenbg5 Jun '11 - 3:20 
Great Job!
Generalno sound being capturedmemberehtsham23882 Jun '11 - 1:01 
hi i am trying this code but it only record sound from mic not from sound card
GeneralRe: no sound being capturedmemberrrossenbg5 Jun '11 - 3:19 
Read yeti.ReadMe.txt
QuestionPInvokeStackImbalance was detectedmemberMember 784199322 Apr '11 - 1:28 
I´m using VS 2010 and wav recording works just fine Laugh | :laugh:
But when i start recording to mp3 i get the PInvokeStackImbalance was detected error at line 89 in Mp3Writer.cs
 
 try
      {
        m_Mp3Config = Mp3Config;
 ==>       uint LameResult = Lame_encDll.beInitStream(m_Mp3Config, ref m_InputSamples, ref m_OutBufferSize, ref m_hLameStream);
        if ( LameResult != Lame_encDll.BE_ERR_SUCCESSFUL)
        {
          throw new ApplicationException(string.Format("Lame_encDll.beInitStream failed with the error code {0}", LameResult));
        }
 
and when i stop the recording i get the same error but at line 384 in Lame.cs
 
 public static uint EncodeChunk(uint hbeStream, byte[] buffer, int index, uint nBytes, byte[] pOutput, ref uint pdwOutput)
    {
      uint res;
      GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
      try
      {
        IntPtr ptr = (IntPtr)(handle.AddrOfPinnedObject().ToInt32()+index);
   ==>     res = beEncodeChunk(hbeStream, nBytes/2/*Samples*/, ptr, pOutput, ref pdwOutput);
      }
      finally
      {
        handle.Free();
      }
      return res;
    }
What should i do to fix this?
GeneralGreat Job!memberDiamonddrake6 Dec '10 - 14:16 
This is a great set up, too many dlls though, I'm working on condensing it into 1 lib + direct x and lame. I am still working on figuring out how to record loopback audio though...
GeneralTranslation in VB.NETmembertratak30 Nov '10 - 11:55 
Hello !
 
Thanks for this project !
It would be fine if we can find a VB.NET version of this project. I've tried to translate it to vb.net but I cannot find some errors; there are problems with automatic translation using programs for this due of different factors (case sensitive/insensitive, etc.).
 
Thank you !
GeneralCapture Audio Output (Not microphone)memberLaserson13 Nov '10 - 3:26 
Hi, great work, but i still can't record audio output? Is it possible to record audio card output with your project?
Generalcrashed with AccessViolationExceptionmembermikecline3 Nov '10 - 10:22 
I tried to run the C# version. It crashed as soon as I pressed the "Sart recording" button. Any thoughts?
 
LINE:
 
_err = API.mciSendCommand(0, API.MCI_OPEN, API.MCI_WAIT | API.MCI_OPEN_TYPE | API.MCI_OPEN_ELEMENT, ptr);
 
MESSAGE:
 
A first chance exception of type 'System.AccessViolationException' occurred in Geming.SimpleRec.exe
An unhandled exception of type 'System.AccessViolationException' occurred in Geming.SimpleRec.exe
 
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
AnswerRe: crashed with AccessViolationExceptionmemberhromoxy27 Sep '11 - 0:26 
Go to Project Properties > Build > Platform Target > Instead "Any CPU" select x86
I hope that will fix problem, it did it for me.
Generalthanx... it's a useful sample,but i have a problem integrating it with my project.memberprasadbuddhika29 Aug '10 - 5:11 
i load your project into my project using reflection.and i used a separate thread to run your project. it loaded with out problem.
but when i click the start button, i got a message(i can't remember). then i debug the code and found that it gives this exception.
"An error occurred invoking the method. The destination thread no longer exists."
i really appreciate if you can give any idea about this.
thank you in advance.
GeneralProblem with downloading examples.memberGyurkin13 Aug '10 - 1:31 
I am very interested in viewing source code of your example, but when I tried to download file using the next link:
 
http://www.codeproject.com/KB/audio-video/Mp3SoundCapture/Mp3Capture.zip[^]
 
my browser was redirected to your article.
 
How I can download your example?
GeneralRe: Problem with downloading examples.memberGyurkin13 Aug '10 - 1:39 
Now this issue was fixed.
May be it is a trouble of codeproject web site.
 
Thanks.
GeneralRecord only internal sound not what ever we talk too and save it as .wav or .mp3 (how)..membersunil1501877 Apr '10 - 20:03 
i want to record what cpu is creting sound but not what we talk to...its just like personal wave recorder..it is also recording what ever we talk too.. but please help me in regarding to capture only system sound and record then save it as mp3 or wav file but not personal things too..pls help me.. its urjent
QuestionPlaying the recorded data?memberMohammad A Gdeisat22 Mar '10 - 4:54 
Is there a way to play the recorded data without saving it to a file (from a memory stream)? Thank you
And ever has it been that love knows not its own depth until the hour of separation
 
Mohammad Gdeisat

GeneralI found a bug in ur Code :-(membermaltub18 Mar '10 - 14:07 
I found that each 1 minutes their is extra one second while recording in real time. in other word if I record 5:00 minutes in real time the resulted sound file will be 5:05 !!! wt is the problem here?
QuestionReal time savingmemberandrea rossetti9 Jan '10 - 4:32 
I need to start the registration of a new audio file, immediatly after stopping the previous.
So I've a problem, saving the first file require a lot of time, and i miss first seconds of second file.
Is it possible to saving file during registration, instead saving file at the end?
AnswerRe: Real time savingmemberkelsett10 Aug '10 - 11:01 
I didnt have a look at the code yet, but i'm sure it's possible to create multiple threads, and when one thread is finished, trigger the next one before saving the first file..
QuestionQuestion about how to runmemberLucrefy21 Dec '09 - 2:37 
Big Grin | :-D i can not run it in vs2005. why? thanks!
GeneralPocket PC portingmemberJossGP25 Nov '09 - 7:44 
Hi Lukasz,
 
Gooood article, thanks,
 
Could you give me any suggestions on how to port this apps to WM 6xx ?
 
I read some words from peter bromberg about coredll functionality in recording audio, but I don't have enough experience to put all the pieces together.
I would like to know which libraries I must use on desktop project and at runtime mobile device, If I can do this and if I could have limits.
 
Thanks in advance ,
Joss
GeneralVolume NormalizationmemberAnoop Unnikrishnan16 Nov '09 - 23:40 
Hi Lukasz,
 
This is a wonderful article, Could you please check the normalization functions...I feel its not working.
 
Regards,
AnoopThumbs Up | :thumbsup:
QuestionJust found this project - couple questionsmemberiamstarbuck14 Nov '09 - 9:56 
I went through most of the postings to-date but I still have some questions and I'm hoping there are quick answers.
 
1. I see there are some licensing considerations for MP3. For anyone who has published a utility using this project, what's the basic process to make sure all formalities properly addressed? I want to make sure anyone who uses my software is doing so legally, and that Lukasz and other authors get proper attribution in the package.
 
2. Any other considerations for distribution? This package has a number of dependencies and there is a chain of author rights that needs to be followed if this is to be distributed properly.
 
3. I see the DirectX and other DLLs are in the package, but:
a) Is it better to use these in a distributed utility?
b) Is it better to create a Setup with dependencies where users can download redistributables, or where existing assemblies on their systems will be used?
c) Maybe the solution is a hybrid, like get licensing permissions to include LAME but compel users to get their own DirectX and whatever else is reuqired?
 
4. I might strip out all of the MP3 handling and just use a subset of this project to record WAV files. Might it be better to use a completely different code base than to strip the MP3 guts out of this fine package?
 
Thanks!!
Questionsquelch functionality?memberbkaratte20 Oct '09 - 21:50 
Is there any possiblity to add a detecting if sound is there that can be recorded or not. I need something like a squelch on a radio. do you know what I mean?
 
thanks a lot in advance Wink | ;)
AnswerRe: squelch functionality?memberLukasz Kwiecinski, Istrib23 Oct '09 - 12:06 
You'd have to tweak the code a bit, but it doesn't look hard. Since the sound goes from DirectX to mp3 encoder through a chain of "filters" (Istrib.Sound.Filters.SoundFilter - actually the mp3 encoder is also an instance of this type - last in the chain), you'd have to write your own filter which would supress any output until the medium volume (i.e. sum(abs(sample value)) accross some time window) exceedes a treshold. Have a look how the volume normalizer filter is implemented and plugged in between DirectX waveform source and mp3 encoder filter: Mp3SoundCapture.cs, Ln 230.
GeneralRe: squelch functionality?memberbkaratte24 Oct '09 - 2:45 
thanks for your reply, I'll have a look there and report you then.
GeneralRe: squelch functionality?memberbkaratte24 Oct '09 - 8:27 
I created a new Class SquelchFilter : BufferFilter overwrited the RewriteData like in PcmNormalizeFilter.
 
Now I'm wondering how I can do something like in the Normalize-Method but for analyzing if sound is incoming or not?
 
Thanks a lot in advance?
GeneralRe: squelch functionality?memberLukasz Kwiecinski, Istrib25 Oct '09 - 11:35 
I think you should rather inherit from SoundFilter than from BufferFilter, since you do not have to buffer whole recording to detect end of silence. When implementing SoundFilter you are responsible to provide an instance of input stream (SoundFilter.Input property). Waveform will be written to that stream. Each byte (or 2bytes or 4bytes, depending on the WAV format) represent a mono or stereo sample. Your filter is then responsible for rewriting that waveform data to SoundFilter.Output stream (instance of this is provided automatically).
InputSplittingStream will be very handy in your case as a value to be exposed from SoundFilter.Input property. InputSplittingStream notifies you about chunks of data (samples) written to it. What you need to do is to handle InputSplittingStream.ChunkWritten event and analyze the actual chunk data. By setting InputSplittingStream.ChunkSize, you specify how often you will be notified about new data in the stream. The rest depends on your definition of silence (there is always some background noise). E.g. if you adjusted the ChunkSize to be of 0.2 sec length (actual number of bytes to be computed from sample rate and wave format), you could assume that sound is detected if the sum of absolute values of samples within the chunk exceeds X. I cannot give you the value of X - you should calibrate it yourself (noise level in a silent room is lower than e.g. in the street). It will be close to zero. So whenever the sum of sum(abs(sample)) > X, you rewrite InputSplittingStream.Input to InputSplittingStream.Output. Otherwise, you don't do it, as it is too silent. What goes to InputSplittingStream.Output would go further through other filters (finally through mp3encoder) and you would get the output without silence.
GeneralRe: squelch functionality?memberbkaratte27 Oct '09 - 13:58 
sorry I tried to get it - but i don't get a proper result.
 
Maybe you can give me a small example. thanks a lot for your help!
GeneralRe: squelch functionality?memberLukasz Kwiecinski, Istrib31 Oct '09 - 12:07 
Unfortunately I am a bit busy at the moment, so the advice is the only one thing I can provide you with. I'm coming back to this component within 1 or 2 months to employ it at http://www.istrib.org. The silence detection is important in this case, so I will probably write a similar filter... Unfortunately not at this moment :(
Generalclean up the sound before saving it to filememberColerudy13 Oct '09 - 16:06 
I have sound coming in from a a Short wave radio through my line in on my sound card that I would like to clean the sound up before listening to it though my computer like DSP(digital signal processing)function of filtering the sound. So I was wondering could I uses this library to accomplish this?
GeneralRe: clean up the sound before saving it to filememberLukasz Kwiecinski, Istrib23 Oct '09 - 12:08 
You would probably find appropriate functionality inside DirectX. If not, you can always write your own filter and plug it into DirectX-mp3encoder chain (like at Mp3SoundCapture.cs, Ln 230).

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 20 Oct 2009
Article Copyright 2008 by Lukasz Kwiecinski, Istrib
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid