.NET NAudio音频录制方法 2021-02-13

news/2023/11/28 17:42:41

.NET NAudio音频录制方法

  • 写在前面
  • 文章主要内容
    • 说明
    • 检测录音电平
    • 调节录音电平
    • 开始录音
    • 调整音频
    • 保存音频
    • 关于作者
    • 讨论
      • SomeONe
      • Clint
      • Nate Greenwood
      • Clint
      • Alejandro
      • gr33x
      • FedeLasse
      • samzhang
      • Miran
      • Denis
      • john
      • Daniel
      • Ryan Smith


.NET 音频录制
.NET Voice Recorder
10月 08, 2009 at 11:29上午
作者:Mark Heath



In this article I demonstrate how to record from the microphone in .NET, with support for setting the recording level, trimming noise from the start and end, visualizing the waveform in WPF and converting to MP3.
Audio Recording in .NET
. net框架没有提供任何对录制音频的直接支持,因此我将使用开放源码的NAudio项目,该项目包括许多Windows音频录制api的包装器。
The .NET framework does not provide any direct support for recording audio, so I will make use of the open source NAudio project, which includes wrappers for a number of Windows audio recording APIs.
注意:需要指出的是,. net不是一个适合于高采样率和低延迟音频录制的选择,例如在录音棚中使用的数字音频工作站软件。这是因为。net垃圾收集器可以在任何时候中断进程。然而,为了从麦克风中录制语音,. net框架的功能远远不止于此。默认情况下,NAudio要求声卡每100ms提供一次数据,这给了垃圾收集器和我们自己的代码运行足够的时间。
Note: It is important to point out that .NET is not an appropriate choice for high sample rate and low latency audio recording, such as that found in Digital Audio Workstation software used in recording studios. This is because the .NET garbage collector can interrupt the process at any point. However, for purposes of recording speech from the microphone, the .NET framework is more than capable. By default, NAudio asks the soundcard to give us data every 100ms, which gives plenty of time for the garbage collector to run as well as our own code.
我们将使用waveIn API的包装器,因为它们是最普遍支持的,并且允许我们自由选择采样率。我们将以8kHz的16位单声道录制,这对于语音来说已经足够好了,而且不会让处理器负担过重,因为我们想要可视化波形,这一点很重要。
We will make use of the wrappers for the waveIn API’s, as these are the most universally supported, and allow us freedom to choose the sample rate. We will record in mono, 16 bit at 8kHz, which is more than good enough audio quality for speech, and will not overly tax the processor, which is important as we want to visualize the waveform as well.
Choosing a Capture Device
通常情况下,你可以毫无困难地使用默认的音频捕获设备,但如果你需要为用户提供选择,NAudio会允许你这么做。你可以使用WaveIn。DeviceCount WaveIn。GetDeviceCapabilities查找存在多少录音设备,并查询它们的名称和支持的通道数量。
Normally, you will be able to use the default audio capture device without any difficulties, but should you need to offer the user a choice, NAudio will allow you to do so. You can use the WaveIn.DeviceCount and WaveIn.GetDeviceCapabilities to find out how many recording devices are present, and query for their name and number of supported channels.
On my computer, I have a single waveIn device (Microphone Array) until I plug my headset in, at which point, a new device appears and becomes the default (device 0 is always the default).

int waveInDevices = WaveIn.DeviceCount;
for (int waveInDevice = 0; waveInDevice < waveInDevices; waveInDevice++)
{WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);Console.WriteLine("Device {0}: {1}, {2} channels", waveInDevice, deviceInfo.ProductName, deviceInfo.Channels);

This produces the following output on my computer:
设备0:麦克风/线路插入(SigmaTel, 2通道
Device 0: Microphone / Line In (SigmaTel , 2 channels
Device 1: Microphone Array (SigmaTel High, 2 channels
Unfortunately these device names are truncated because the WAVEINCAPS structure only supports 31 characters. There is a way of getting the full device name, but it is rather convoluted.
Normally, you will choose Device 0 (the default), but if you wish to select a different input device, simply set the DeviceNumber property on your WaveIn object to the desired number.


Checking the Recording Level
录音的第一步通常是帮助用户确定他们的麦克风是否工作。如果用户的声卡上有多个输入,这一点尤其重要。我们实现这一点的方式很简单,通过开始记录和显示音频水平检测到用户与音量计。waveIn api不会把任何东西写到磁盘上,所以在这一点上没有音频被“录制”,我们只是检查输入电平,然后扔掉捕获的音频样本。
The first step in recording is usually to help the user determine if their microphone is working or not. This is especially important if the user has more than one input on their soundcard. The way we achieve this is simply by starting recording and displaying the level of audio detected to the user with a volume meter. The waveIn APIs do not write anything to disk, so no audio is actually being ‘recorded’ at this point, we are simply examining the input level and then throwing the captured audio samples away.
To begin capturing audio from the soundcard, we use the WaveIn class in NAudio. We configure it with the WaveFormat in which we would like to record (in our case 8kHz mono), before calling StartRecording, to start capturing audio from the device.

waveIn = new WaveIn();
waveIn.DeviceNumber = selectedDevice;
waveIn.DataAvailable += waveIn_DataAvailable;
int sampleRate = 8000; // 8 kHz
int channels = 1; // mono
waveIn.WaveFormat = new WaveFormat(sampleRate, channels);

The DataAvailable event handler will notify us whenever a buffer of audio has been returned to us from the sound card. The data comes back as an array of bytes, representing PCM sample data. This is fine if we are planning to write the audio directly to disk, but what if we wish to have a look at the audio data itself? Each audio sample is 16 bits, i.e. two bytes, meaning that we will need to convert pairs of bytes into shorts to be able to make sense of the data.
Note: if we were recording in stereo, the 16 bit samples would themselves come in pairs, first the left sample, then the right sample.
The following code shows how we might process the raw bytes in the DataAvailable event, and read the individual audio samples out. Notice that we use the BytesRecorded field, not the buffer’s Length property. Also, I have chosen to convert the samples to 32 bit floating point format and scaled them so the maximum volume is 1.0f. This makes processing them through effects and visualizing them much easier.

void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{for (int index = 0; index < e.BytesRecorded; index += 2){short sample = (short)((e.Buffer[index + 1] << 8) | e.Buffer[index + 0]);float sample32 = sample / 32768f;ProcessSample(sample32);}

注意:使用waveIn和waveOut api的一个复杂之处是决定回调机制。NAudio提供了三种选择。首先是函数回调。这意味着waveIn API被赋予了一个(固定的)函数指针,并被它调用。这意味着DataAvailable回调将在后台线程中进入。在某种程度上,这是最干净的方法,但你需要小心使用函数回调时可能挂起对waveOutReset调用的恶意声卡驱动程序(在许多笔记本电脑上发现的SoundMAX芯片组特别容易出现这个问题)。
Note: One complication of using the waveIn and waveOut APIs is deciding on a callback mechanism. NAudio offers three options. First is function callbacks. This means that the waveIn API is given a (pinned) function pointer which it calls back onto. This means that your DataAvailable callback will come in on a background thread. In some ways this is the cleanest approach, but you need to beware of rogue soundcard drivers that can hang in calls to waveOutReset when using function callbacks (the SoundMAX chipset found on a lot of laptops is particularly prone to this problem).
第二种方法是提供窗口句柄。waveIn api会在窗口句柄的消息队列中返回一个待处理的消息。这种方法往往是最可靠和最常用的。需要注意的一个问题是,如果您停止录制并立即重新启动,来自旧录制会话的消息可能会在新会话中处理,从而导致严重的异常。
The second is to supply a window handle. The waveIn APIs will post a message back to be handled on the message queue of that window handle. This method tends to be the most reliable and most commonly used. One gotcha to watch out for is that if you stop recording and immediately restart, a message from the old recording session could get handled in the new session resulting in a nasty exception.
The third is to let NAudio create its own new window and post messages to that. This gets round any danger of messages from one recording session getting muddled up with another. This is the callback method that NAudio will use by default if you call the default WaveIn constructor. But don’t use this from a background thread or from a console application, or the new window that NAudio creates won’t actually get round to processing its message queue.
Visualizing the Recording Level
We have seen how we can begin to capture audio from the soundcard for the purposes of checking the recording level. Now we need to give the user some visual feedback. We will use WPF for our sample recording application. The simplest control we have available to display a single numeric value graphically is the ProgressBar. And because it is WPF, we can fully customize the graphical appearance of the progress bar to look a little more like a volume meter. I have used a gradient going from green to red to show the current volume level. You can read more about how I created this ProgressBar template here.


Figure 1 - A Progress Bar Showing the Current Microphone Volume Level
To help provide the volume level to display, I have created a SampleAggregator class. This is passed every audio sample value we receive and keeps track of the maximum and minimum values. Then, after a specified number of samples, it raises an event allowing the GUI components to respond. We need to be careful not to raise too many of these events or performance will be badly affected. I am raising one every 800 samples, meaning we get 10 updates per second to the screen.
Because I am using data binding, when one of these updates fires, I must raise a PropertyChangedEvent on my DataContext object (also known as the “ViewModel” in the MVVM pattern). Here’s the XAML syntax for binding to my CurrentInputLevel property:

<ProgressBar Orientation="Horizontal" Value="{Binding CurrentInputLevel, Mode=OneWay}" Height="20" />

And here’s the code in the ViewModel that ensures that the GUI updates whenever we calculate a new maximum input level:

private float lastPeak;void recorder_MaximumCalculated(object sender, MaxSampleEventArgs e) 
{lastPeak = Math.Max(e.MaxSample, Math.Abs(e.MinSample));RaisePropertyChangedEvent("CurrentInputLevel");


// multiply by 100 because the Progress bar's default maximum value is 100 
public float CurrentInputLevel { get { return lastPeak * 100; } }

Note: Model View ViewModel (MVVM) is a pattern that is growing in popularity amongst WPF and Silverlight developers. The basic idea is that you have no code behind whatsoever on your View (i.e. your xaml markup file), and simply specify all communications with your business logic by means of data binding. The ViewModel serves as an adapter to ease the process of data binding. This approach gives very good separation of appearance and behavior. For the most part, this pattern works very well, but there are a few tricky areas, for which you will need to either write a few lines of code behind, or make use of some cunning tricks such as attached dependency properties or custom triggers. There are several excellent open source helper libraries that can take some of the work out of getting an MVVM application up and running. Have a look here for a comprehensive list.


Adjusting the Recording Level
Suppose the current input level is too high or too soft. We would like to be able to support modifying the recording level. Again, we would like to use data binding to do so, so we will add a volume slider to our XAML:

<Slider Orientation="Horizontal" Value="{Binding MicrophoneLevel, Mode=TwoWay}" Maximum="100" Margin="5" />

现在我们必须掌握MixerLine,它将允许我们访问我们的waveIn设备的输入音量控制。这要求我们使用Windows mixer api,它在NAudio中也有包装器。获得这个音量控制并不总是像你可能希望的那样简单(并且可能需要不同的方法为XP和Vista),但以下是代码,似乎在大多数系统上工作:
Now we have to get hold of the MixerLine that will allow us to access the input volume control for our waveIn device. This requires us to make use of the Windows mixer APIs, which also have wrappers in NAudio. Getting hold of this volume control is not always as straightforward as you might hope (and can require different approaches for XP and Vista), but the following is code that seems to work on most systems:

private void TryGetVolumeControl()
{int waveInDeviceNumber = 0;var mixerLine = new MixerLine((IntPtr)waveInDeviceNumber, 0, MixerFlags.WaveIn);foreach (var control in mixerLine.Controls){if (control.ControlType == MixerControlType.Volume){volumeControl = control as UnsignedMixerControl;        break;}}

Now we can use the Percent property on the UnsignedMixerControl to set volume to a value anywhere between 0 and 100.


Starting Recording
Now we have got our recording levels set up correctly, we are ready to actually start recording. But since we have already opened our waveIn device, all we need to do is start writing the data we have received into a file.
NAudio has a class called WaveFileWriter which will allow us to write our recorded data to a file. For now, we will write it to a temporary file in PCM format, and convert it later into a better compressed format such as MP3. The following code creates a new WAV file:
writer = new WaveFileWriter(waveFileName, recordingFormat);
Now we can write to the file as we receive notifications from the waveIn device:

void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{if (recordingState == RecordingState.Recording)writer.WriteData(e.Buffer, 0, e.BytesRecorded);            // ...

Note: There are three main options for how to store audio while it is being recorded. First, you can write it to a MemoryStream. This saves the inconvenience of dealing with a temporary file, but you need to be careful not to run out of memory. Also, if your recording program crashes half way through, you have lost everything. At the sample rate we are using for this demo, one minute of audio takes just under 1 MB of memory, but if you were recording at 44.1kHz stereo (the standard for music), you would need about 10 MB per minute.
Second, you can write to a temporary WAV file to be converted to another format later, as we are doing here. While this is not a disk space efficient format, it is very easy to work with, and particularly useful if you are planning to apply any effects or edit the audio in any way after recording.
Third, you can pass the audio directly to an encoder (such as WMA or MP3) as it is being recorded. This might be the best option if you are making a longer recording, and have no need to edit it after recording.
显然,当用户单击stop recording按钮时,我们将停止,但我们也可能希望设置一个最大的记录持续时间,以阻止用户无意中填满他们的硬盘。在这个例子中,我们将允许一分钟的录音。
Stopping Recording
Obviously we will stop when the user clicks the stop recording button, but we might also want to set a maximum recording duration to stop the user inadvertently filling up their hard disk. For this example, we will allow one minute of recording.

long maxFileLength = this.recordingFormat.AverageBytesPerSecond * 60;int toWrite = (int)Math.Min(maxFileLength - writer.Length, bytesRecorded);
if (toWrite > 0)writer.WriteData(buffer, 0, bytesRecorded);

Note: Something that can be slightly confusing for users is that when using window callbacks with WaveIn, the last bit of audio you recorded comes in after you have asked recording to stop, so make sure you don’t close the file you are saving to until you have got all the audio back. The FinishedRecording event on the WaveIn object will help you determine when it is safe to close the WaveFileWriter and clean up your resources.
Visualizing the Wave Form
It is often desirable to display the audio waveform to the user. Displaying the waveform while you are recording is sometimes called “confidence recording”, because it allows you to see that audio is being recorded as expected and the levels are still right.
There are a variety of possible approaches for drawing audio waveforms. The simplest is to draw a vertical line showing the minimum and maximum values every time our sample aggregator fires:

图2 -使用垂直线的音频波形
Figure 2 - Audio Waveform using vertical lines
At first glance it may seem that this would be trivial to implement in WPF, but there is a real danger of consuming too many resources. For example, simply adding a new line to a Canvas every time a new maximum sample is calculated performs very badly, so it is better to have a fixed number of vertical lines and resize them dynamically.
Another approach is to create a polygon. This requires us to add two points to a Polygon’s Points collection every time we receive a new sample. The trick is to add these points in the middle of the Points collection, rather than at the end, so that the end result is a single shape. This means our waveform can have a different outline color and fill color. To stop the edges from appearing too jagged, we plot points two units apart along on the X axis.


图3 -使用多边形渲染的音频波形
Figure 3 - Audio Waveform rendered using a Polygon
Like the microphone volume meter, the waveform drawing control needs to receive several notifications a second of the maximum and minimum sample values received by the SampleAggregator. When each sample value is received, we either insert new points into our polygon, or, if the whole screen is full, we go back to the left-hand edge and continue drawing from there.
For the confidence recording display I have used the Polygon method, which is in a class called PolygonWaveFormControl. Here’s the code which calculates the new points or updated point locations as we receive a new maximum sample:

public void AddValue(float maxValue, float minValue)
{int visiblePixels = (int)(ActualWidth / xScale);if (visiblePixels > 0){CreatePoint(maxValue, minValue);if (renderPosition > visiblePixels){renderPosition = 0;}int erasePosition = (renderPosition + blankZone) % visiblePixels;if (erasePosition < Points){double yPos = SampleToYPosition(0);waveForm.Points[erasePosition] = new Point(erasePosition * xScale, yPos);waveForm.Points[BottomPointIndex(erasePosition)] = new Point(erasePosition * xScale, yPos);}}
}private void CreatePoint(float topValue, float bottomValue)
{double topYPos = SampleToYPosition(topValue);double bottomYPos = SampleToYPosition(bottomValue);double xPos = renderPosition * xScale;if (renderPosition >= Points){int insertPos = Points;waveForm.Points.Insert(insertPos, new Point(xPos, topYPos));waveForm.Points.Insert(insertPos + 1, new Point(xPos, bottomYPos));}else{waveForm.Points[renderPosition] = new Point(xPos, topYPos);waveForm.Points[BottomPointIndex(renderPosition)] = new Point(xPos, bottomYPos);}renderPosition++;

erase position的计算是为了将之前的一些示例值清空,以便在我们绕完一次后,新数据出现的地方更加明显:
The erase position calculation is to blank out some previous sample values to make it obvious where the new data is appearing after we have wrapped around once:

图4 polygon波形控制的“空白区域”
Figure 4 PolygonWaveForm control’s “blank zone”
Note: There are faster ways to perform rendering in WPF. One option is to use the WriteableBitmap class and draw directly onto it. This could be a good approach if you were using the vertical lines method of rendering. The second is to use DrawingVisual objects, which are lightweight drawing objects offering better performance than using classes derived from Shape. The down-side is the loss of features such as DataBinding and the ability to fully describe the picture in XAML, but for WaveForm drawing this is not really a drawback. I use the DrawingVisual method in the Save Audio part of this application.
Another challenge was how the waveform drawing control could receive notifications since I am using MVVM so I have no direct access to the SampleAggregator. A simple way around this was to create a Dependency Property on PolygonWaveFormControl:

public static readonly DependencyProperty SampleAggregatorProperty = DependencyProperty.Register("SampleAggregator", typeof(SampleAggregator), typeof(PolygonWaveFormControl), new PropertyMetadata(null, OnSampleAggregatorChanged));public SampleAggregator SampleAggregator
{get { return (SampleAggregator)this.GetValue(SampleAggregatorProperty); }set { this.SetValue(SampleAggregatorProperty, value); }
}private static void OnSampleAggregatorChanged(object sender, DependencyPropertyChangedEventArgs e)
{PolygonWaveFormControl control = (PolygonWaveFormControl)sender;control.Subscribe();

This allows us to bind the PolygonWaveFormControl to the SampleAggregator made public on our DataContext:

<my:PolygonWaveFormControl Height="40" SampleAggregator="{Binding SampleAggregator}" />


Trimming the Audio

We have created a temporary WAV file, but before the user saves it to a file of their choosing, we want to allow them to trim off any unwanted parts from the start and end of the recording. To do this I would like to display the entire recorded waveform, with a selection rectangle superimposed on top to allow a sub-range to be selected.

图5 - GUI允许选择录制音频的一部分
Figure 5 - GUI to allow selection of a portion of the recorded audio
To accomplish this kind of interface we need three components. The first is a ScrollViewer. The ScrollViewer allows us to scroll left and right through the WaveForm if it is too big to fit onto a screen, which is likely if you record more than a few seconds of audio.
第二种是一种新型波形渲染器,它将渲染整个文件,而不是我的PolygonWaveFormControl,它在屏幕填满时从左边开始。为此,我创建了WaveFormVisual,它使用DrawingVisual objects来绘制整个波形。显然,如果我们想要长时间记录,这种方法就需要进行优化,因为它创建的多边形将拥有数千个点,但对于短记录来说,它的效果很好。
The second is a new type of WaveForm renderer that will render an entire file, rather than my PolygonWaveFormControl which started again at the left when the screen filled up. For this I created WaveFormVisual which uses DrawingVisual objects to draw the entire WaveForm. Obviously if we wanted to record for a long period, this approach would need to be optimised as the polygon it creates would have thousands of points, but for short recordings, it works fine.
The third piece was the hardest to get right – the selection rectangle to support mouse dragging selection of the waveform. For this I created the RangeSelectionControl.
The RangeSelectionControl is simply a blue rectangle with a solid outline and semi-transparent fill sitting on a Canvas. The magic occurs in the mouse handler. We need to detect when the user hovers over the left or right edge of the rectangle, and set the cursor to show a horizontal resizing icon. This can be done in the MouseMove event, checking the X coordinate and then setting the Cursor property:
Cursor = Cursors.SizeWE;
When the user clicks the left-button while over the edge, we begin to drag. Key to this is calling Canvas.CaptureMouse. If we don’t do this, as soon as you try to drag the rectangle bigger, the mouse move events are lost to other controls underneath.

void RangeSelectionControl_MouseDown(object sender, MouseButtonEventArgs e)
{if (e.LeftButton == MouseButtonState.Pressed){Point position = e.GetPosition(this);Edge edge = EdgeAtPosition(position.X);DragEdge = edge;if (DragEdge != Edge.None){mainCanvas.CaptureMouse();}}

Now in the MouseMove methods, we can change the Canvas.Left and Width properties of the rectangle to resize it.
The ScrollViewer is quite straightforward to use, but you must remember to set CanContentScroll property to true, and also to set the size of the items within the ScrollViewer correctly.

<ScrollViewer CanContentScroll="True" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Hidden"><Grid><my:WaveFormVisual Height="100" HorizontalAlignment="Left" x:Name="waveFormRenderer"/><my:RangeSelectionControl HorizontalAlignment="Left" x:Name="rangeSelection" /></Grid>

We set the appropriate Width of the WaveFormVisual and RangeSelectionControl based on the total number of points we have drawn in the waveform.


Saving the Audio
So we are finally ready to save the audio. We will offer the user two choices of format to save in. The first is simply to save as a WAV file. If the user has selected the entire recording, we only need to copy the audio across to their desired location. If, however, the user has selected a sub-range, then we need to trim the WAV file. This can be quickly accomplished using a TrimWavFile utility function that copies from a WAV file reader to a WAV file writer, skipping over a certain number of bytes from the beginning and end.

public static void TrimWavFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)
{using (WaveFileReader reader = new WaveFileReader(inPath)){using (WaveFileWriter writer = new WaveFileWriter(outPath, reader.WaveFormat)){int bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;int startPos = (int)cutFromStart.TotalMilliseconds * bytesPerMillisecond;startPos = startPos - startPos % reader.WaveFormat.BlockAlign;int endBytes = (int)cutFromEnd.TotalMilliseconds * bytesPerMillisecond;endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;int endPos = (int)reader.Length - endBytes; TrimWavFile(reader, writer, startPos, endPos);}}
}private static void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPos, int endPos)
{reader.Position = startPos;byte[] buffer = new byte[1024];while (reader.Position < endPos){int bytesRequired = (int)(endPos - reader.Position);if (bytesRequired > 0){int bytesToRead = Math.Min(bytesRequired, buffer.Length);int bytesRead = reader.Read(buffer, 0, bytesToRead);if (bytesRead > 0){writer.WriteData(buffer, 0, bytesRead);}}}

我们还想提供保存为MP3的功能。创建MP3文件最简单的方法是使用开源的LAME MP3编码器(如果你还没有这个应用程序,可以在web上搜索LAME .exe来获得它)。我们的应用程序将在当前目录中查找,并提示用户找到lame.exe(如果它不存在),因为我们没有将它包含在应用程序下载中。假设您确实提供了一个有效的路径,那么我们就可以通过使用适当的参数调用lame.exe将我们的(修改过的)WAV文件转换为MP3。
We also want to offer the ability to save as MP3. The easiest way to create MP3 files is to use the open source LAME MP3 encoder (do a web search for lame.exe to get hold of this application if you haven’t already got it). Our application will look in the current directory, and prompt the user to find lame.exe if it is not present, as we do not include it in the application download. Assuming you do provide a valid path, we can then convert our (trimmed) WAV file to MP3 by simply calling lame.exe with the appropriate parameters.

public static void ConvertToMp3(string lameExePath, string waveFile, string mp3File)
{Process converter = Process.Start(lameExePath, "-V2 \"" + waveFile + "\" \"" + mp3File + "\"");converter.WaitForExit();

We end up with a nice compact MP3 file containing the selected portion of our microphone recording.
Exploring the Sample Code Solution
主要的WPF示例应用程序可以在VoiceRecorder项目中找到。它包含了主窗口以及三个视图及其关联的视图模型。VoiceRecorder。Core包含一些WPF helper类和用户控件,以帮助处理应用程序的管道和GUI,而VoiceRecorder。Audio包含实际执行音频录制、编辑和转换的类。
The main WPF sample application is found in the VoiceRecorder project. This contains the main window along with the three views and their associated ViewModels. VoiceRecorder.Core contains some WPF helper classes and user controls to help with the plumbing and GUI of the application, while VoiceRecorder.Audio contains the classes that actually perform the recording, editing and converting of audio.


About the Author
Mark Heath是一名软件开发者,目前在英国南安普顿的NICE CTI系统公司工作。他专门从事。net开发,特别关注客户端技术和音频播放。他在http://mark-dot-net.blogspot.com上有关于音频、WPF、Silverlight和软件工程最佳实践的博客。他是CodePlex上几个开源项目的作者,其中包括NAudio,一个底层的。net音频工具包(http://www.codeplex.com/naudio)。
Mark Heath is a software developer currently working for NICE CTI Systems in Southampton, UK. He specializes in .NET development with a particular focus on client side technologies and audio playback. He blogs about audio, WPF, Silverlight and software engineering best practices at http://mark-dot-net.blogspot.com. He is the author of several open source projects hosted at CodePlex, including NAudio, a low-level .NET audio toolkit (http://www.codeplex.com/naudio).



I like the fact that you don’t gloss over architecture. One might think that because it is Coding4Fun that the design would be flat and monolithic. You have separate assemblies exposing different levels of functionality. You also have various implementations or the start of some common design patterns. Like IoC, Command Mediator, Helper/Services, MVVP, etc. This is being done without saying to much about it other than a small blurb on MVVP. Great Job!
上次修改时间: 10月 08, 2009 at 9:00下午


@Nate Greenwood, we may or may not have an article in the works for that
上次修改时间: 10月 08, 2009 at 9:00下午

Nate Greenwood

Awesome. Great article, and just in time as I was pondering a project to learn to take advantage of my built-in monitor webcam and microphone.
上次修改时间: 10月 08, 2009 at 9:00下午
you make an incredible job, im your fans!!
上次修改时间: 10月 08, 2009 at 9:00下午


@SomeONe Thanks man, we try to make the articles both useful and show useful ways of doing stuff. May not always be successful but we try.
上次修改时间: 10月 09, 2009 at 9:00下午
Robson Felix
Can this be used inside an XAML Browser Application (XBAP)?
上次修改时间: 3月 16, 2010 at 9:00下午


How can I change the recording time to a value bigger than 60 seconds???
上次修改时间: 1月 12, 2011 at 9:00下午


you do the best tutorials… that was really nice explained… congrats to autors
上次修改时间: 6月 04, 2011 at 7:03上午


This has to be the most useful article on audio there has come to exist for C# programmers. Thanks a LOT for it! It’ll help me develop my program for sure.
上次修改时间: 7月 23, 2011 at 3:15下午
Bram Osterhout
I want to save a series of notes/sounds which I had in an array which stored each note’s frequency, amplitude, and duration. What would be the procedure for accomplishing this?
上次修改时间: 9月 03, 2011 at 5:35下午


上次修改时间: 9月 10, 2011 at 5:44上午


Replay at person asking how to remove limit of 60 seconds.
in AudioRecorder.cs of the project change the writetofile Function to following.

private void WriteToFile(byte[] buffer, int bytesRecorded)
if (recordingState == RecordingState.Recording
|| recordingState == RecordingState.RequestedStop)
{writer.WriteData(buffer, 0, bytesRecorded);

Go to your solution and delete voicerecorder.audio and core DLLs.
Add refrences and Browse to bin location of the built voicerecorder project and import those DLL. Seeing how the voicerecorder project was on my desktop the dll location is.
Voila the limit is totaly removed.
上次修改时间: 10月 08, 2011 at 8:52上午


Thank you! It is exactly what I’ve needed!
上次修改时间: 10月 13, 2011 at 12:21上午


So what happened to: waveIn.DeviceNumber = selectedDevice;
I’ve been trying to figure out how to select a device. I thought NAudio would make capturing mic audio easy. Unfortunately, it appears that all the examples were written befor the changes to the DLL.
OK, how do I select my sound card now?
上次修改时间: 1月 03, 2012 at 12:33下午


@John -如果你注意到,在第一部分他给出了一个例子,如何看当前可用的设备,之后,您可以使用他们的“id”返回waveInDevice方法,对于第一个示例,在大多数情况下是0(默认设备)所以你需要设置waveIn。DeviceNumber = 0;在您的代码中。
@John - if you noticed, in the first part he gives an example of how to see the devices currently available, after that you can use their “id’s” returned by waveInDevice method in that for at the beginning of the example, in most of the cases will be 0 (default device) so actually you’ll need to set waveIn.DeviceNumber = 0; in your code.
上次修改时间: 1月 18, 2012 at 5:56上午

Ryan Smith

Probably a really really ignorant question but this is the first time I’ve been on this site, could someone please tell me what wavein is and where it has come from? Would be much appreciated.
上次修改时间: 1月 29, 2012 at 8:20上午



HuangTools 绿色软件包 (Version 1.0.0)

HuangTools介绍&#xff1a; HuangTools.iso是由本人收藏多年的一些优秀软件打包而成&#xff08;当然是基于Windows平台&#xff09;&#xff0c;Version1.0提供20个常用软件&#xff0c;无论是做学术或者工作&#xff0c;都是可以提升效率的工具。 软件都是绿色免安装单文件…


1.音频采样率及采样精度 1.1采样频率 采样的过程就是将通常的模拟音频信号的电信号转换成二进制码 0 和 1 的过程&#xff0c;这些 0 和 1 便构成了 数字音频文件。图中的正弦曲线代表原始音频曲线&#xff0c;方格代表采样后得到的结果&#xff0c;二者越吻合说明采 样结果越…


一、视频数据源分析 一&#xff09;、视频数据源分析 数字技术就是用数字编码来描述和表达图像、声音等各种媒体信息。其信息处理的流程是&#xff1a;模拟信息→数字化→压缩编码→存储或传输→解码再现。 数字化视频的过程&#xff0e;通常被叫做数字化视频采集。模拟信号到…


原文地址为&#xff1a; 把CDLinux制作成U盘启动 因为用下了CDlinux,本来想在虚拟机上运行的。发现虚拟机跑的时候无法识别集成的笔记本网卡&#xff0c;坑爹啊。后来想刻碟的&#xff0c;发现手头上还没有现成的东西&#xff0c;光驱是只读的&#xff0c;又要用到光驱&#x…


面向对象的七大设计原则 一、单一职责原则 介绍 一个对象应该只包含单一的职责&#xff0c;并且该职责被完整地封装在一个类中。 就一个类而言&#xff0c;应该仅有一个引起它变化的原因。 分析 一个类&#xff08;或者大到模块&#xff0c;小到方法&#xff09;承担的职责越…


计算机网络背景 1.局域网和广域网 1、广域网&#xff1a;是连接不同地区局域网或城域网计算机通信的远程网。 2、局域网&#xff1a;是局部地区形成的一个区域网络&#xff0c;分布地区范围有限。 所谓 "局域网" 和 "广域网" 只是一个相对的概念; 比如, 一…


1、 7-Zip是软件盒子极力推荐的免费开源的拥有极高压缩比压缩软件&#xff01;无论是你是个人还是用于商业&#xff0c;您都可以在任何电脑上使用它&#xff0c;并不需要对 7-Zip 付钱&#xff01;7-zip使用了 LZMA 与 LZMA2 算法的 7z 格式 拥有比同类软件更高的压缩比&#x…

宝藏 解压缩软件——bandzip

免费软件 (无广告/间谍软件/病毒)、一切皆可解压 目录 bandzip介绍搜索bandzip下载exe文件安装与自定义 bandzip介绍 Bandizip 是一个强大的多功能压缩文件管理工具&#xff0c;可提供很快的解压缩速度和其他各种实用功能。软件免费&#xff0c;其付费版本更是可以使用更多的实…


文章目录 1、创建模板2. 创建mapper.xml文件 1、创建模板 打开创建模板页面 位置&#xff1a;File-》Settings-》Editor-》File and Code Templates 点击号&#xff0c;新建模板&#xff0c;填入Name&#xff08;随意&#xff09;、Extension&#xff08;必须为xml&#xff…


目录 前言 题目列表&#xff1a; 题目解析 一维数组 字符数组 字符串 字符指针 二维数组 笔试题 总结 前言 前几期的博客已经将有关指针、数组的所以知识都已基本讲解完毕&#xff0c;那么接下来我们就做一些练习巩固&#xff0c;这些练习依据历年来一些公司笔试题进行…


1、F4&#xff0c;重复上一步&#xff0c;可以当做格式刷、对齐、或者重复做某件事 插入多行&#xff0c;可以先插入一行&#xff0c;然后不断F4 多个地方需要标记颜色&#xff0c;标记一个地方&#xff0c;其它地方不断F4 2、文字中填充图片 选中文本框&#xff0c;右键设置形…

【怎么制作ppt】Focusky教程 | 文字格式刷

在Focusky&#xff08;也称为“FS软件”&#xff09; 动画演示的制作的过程中&#xff0c;使用 “格式刷“ 可以复制已选择的文字的格式&#xff0c; 并应用到其他的文字。 具体步骤如下&#xff1a; 选中要复制格式的文本-单击“格式刷”图标-单击要应用格式的文本 【▲图1…


我们选中一个文本框的一些字&#xff0c;然后双击格式刷 就可以涮多个啦 ~~~~


iSlide插件神器——助您节约90%的PPT设计时间 iSlide插件官方网站&#xff1a;iSlide- 让PPT设计简单起来 | PPT模板下载平台 下载、加载 格式里面有取色器&#xff0c;可以进行取色以及图标的颜色更改。 通过资源库的智能图标按钮可以智能图标的编辑。 通过iSlide下载精美的…

第6章 PPT页面排版与高级设计技术

6.1 形状和线条对排版的影响-理念分享 6.2 形状和线条对排版的影响-基础操作 双击“格式刷”&#xff0c;可以把格式刷可以刷无数次。按ESC或者再点击一次格式刷就可以退出。 6.3 形状和线条对排版的影响-实战操作 不规则图形 此外&#xff0c;还可以利用图形的布尔运算进行不…


学习来源&#xff1a;B站资源https://www.bilibili.com/video/BV1w54y1Q7cZ?p2&spm_id_frompageDriver 一、Shift 1、垂直、水平移动 按住【Shift】之后&#xff0c;拖动&#xff0c;就可以实现只沿垂直或者水平方向移动。 2、等比例放大和缩小 按住【Shift】之后插入的…


Redis configuration file example. 使用/path/to/redis.conf的文件启动redis-server ./redis-server /path/to/redis.conf Note on units: when memory size is needed, it is possible to specify it in the usual form of 1k 5GB 4M and so forth: 1k > 1000 bytes 1k…

ppt如何替换其他mo ban_如何制作PPT教程:PPT排版格式技巧汇总

2分钟掌握8个窍门&#xff0c;看完还不会就别谈PPT了&#xff01; 大家都希望自己做出的PPT能一鸣惊人&#xff0c;升职加薪&#xff0c;迎娶白富美&#xff0c;从此过上幸福人生~ 可是现实是&#xff0c;你不懂排版、不懂配色&#xff0c;做出来的PPT不仅难看&#xff0c;还因…


今天做ppt时&#xff0c;突然想给ppt加个页码&#xff0c;以记录播放进度&#xff0c;于是找到了加页码的方法&#xff0c;后来又找到了进度条的方法&#xff0c;很酷&#xff01; 看到大家比较喜欢&#xff0c;2022年对此文章增加图文&#xff01;&#xff01;&#xff01;&am…

第1章第21节:效率:如何通过格式刷将样式快速复制到其它对象 [PowerPoint精美幻灯片实战教程]

使用格式刷,可以将一个对象上的字体、颜色、填充、边框、段落等所有样式,快速复制到另一个对象,从而大幅提高幻灯片的制作效率。 首先修改所选文字的字体,点击此处的下拉箭头,显示系统字体列表。 在打开的字体列表中,选择一款字体,作为所选文字的字体。 点击增加字号…