using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NAudio.Wave;
using System.IO;
namespace TestAudio
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private IWaveIn waveIn;
private WaveFileWriter writer;
List<float> sampleAggregator = new List<float>();//用来储存波形数据
private void btnStart_Click(object sender, EventArgs e)
{
StartRecording();
} /// <summary>
/// 开始录音
/// </summary>
private void StartRecording()
{
if (waveIn != null) return;
Text = "start recording....";
btnStart.Text = "正在录制....";
btnStart.Enabled = false; waveIn = new WaveIn { WaveFormat = new WaveFormat(8000, 1) };//设置码率
writer = new WaveFileWriter("test.wav", waveIn.WaveFormat);
waveIn.DataAvailable += waveIn_DataAvailable;
waveIn.RecordingStopped += OnRecordingStopped;
waveIn.StartRecording();
} /// <summary>
/// 录音中
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{ writer.Write(e.Buffer, 0, e.BytesRecorded);
byte[] buffer = e.Buffer;
int bytesRecorded = e.BytesRecorded; for (int index = 0; index < e.BytesRecorded; index += 2)
{
short sample = (short)((buffer[index + 1] << 8) |
buffer[index + 0]);
float sample32 = sample / 32768f;
sampleAggregator.Add(sample32);
} int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond);//录音时间获取
if (secondsRecorded >= 3)//只录制6秒
{
waveIn.StopRecording();
Text = "complete";
btnStart.Text = "开始录制";
btnStart.Enabled = true; //------------------------------------开始画波形图。
Text = sampleAggregator.Min() + "," + sampleAggregator.Max();
int baseMidHeight = 50;
float h = 0;
for (int i = 0; i < sampleAggregator.Count; i+=60) {//大概意思意思 60的步长是怕太多了。 h= sampleAggregator[i] * 300;
flowLayoutPanel1.Controls.Add(new Label() { BackColor = Color.Pink, Width = 5, Height = (int)h, Margin = new Padding(0, baseMidHeight-(int)h, 0, 0) }); }
//----------------------------------------------------- } }
/// <summary>
/// 停止录音
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnRecordingStopped(object sender, StoppedEventArgs e)
{ if (waveIn != null) // 关闭录音对象
{
waveIn.Dispose();
waveIn = null;
}
if (writer != null)//关闭文件流
{
writer.Close();
writer = null;
}
if (e.Exception != null)
{
MessageBox.Show(String.Format("出现问题 " + e.Exception.Message));
} } private void Form1_Load(object sender, EventArgs e)
{ } }
}

  

WPF 例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using NAudio.Wave;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace TestAudioWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{ InitializeComponent();
listView.DataContext = listView.ItemsSource = sampleAggregator; } private IWaveIn waveIn;
private WaveFileWriter writer;
ObservableCollection<WaveInfo> sampleAggregator = new ObservableCollection<WaveInfo> ();//用来储存波形数据 /// <summary>
/// 开始录音
/// </summary>
private void StartRecording()
{
if (waveIn != null) return;
Title = "start recording....";
btnStart.Content = "正在录制....";
btnStart.IsEnabled = false;
sampleAggregator.Clear(); waveIn = new WaveIn { WaveFormat = new WaveFormat(8000, 1) };//设置码率
writer = new WaveFileWriter("test.wav", waveIn.WaveFormat);
waveIn.DataAvailable += waveIn_DataAvailable;
waveIn.RecordingStopped += OnRecordingStopped;
waveIn.StartRecording();
} /// <summary>
/// 录音中
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{ writer.Write(e.Buffer, 0, e.BytesRecorded);
byte[] buffer = e.Buffer;
int bytesRecorded = e.BytesRecorded; //------------------------------------开始画波形图。
sampleAggregator.Clear();//可以不清除,就会一直保持历史记录

//  short s = BitConverter.ToInt16(e.Buffer, 0);//这样采样比较少,反正是int16型的
                           //  int w= Math.Abs(s / 50);
                          //  sampleAggregator.Add(new WaveInfo() { heigth = w });

            for (int index = 0; index < e.BytesRecorded; index += 2)
{
short sample = (short)((buffer[index + 1] << 8) |
buffer[index + 0]);
float sample32 = sample / 32768f; if (sample32 > 0.03f)
{
sampleAggregator.Add(new WaveInfo() { heigth = sample32*300f });
}
} //--------------------------------------------------------- int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond);//录音时间获取
if (secondsRecorded >= 552)//只录制552秒
{
waveIn.StopRecording();
Title = "complete";
btnStart.Content = "开始录制";
btnStart.IsEnabled = true; }
} /// <summary>
/// 停止录音
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnRecordingStopped(object sender, StoppedEventArgs e)
{ if (waveIn != null) // 关闭录音对象
{
waveIn.Dispose();
waveIn = null;
}
if (writer != null)//关闭文件流
{
writer.Close();
writer = null;
}
if (e.Exception != null)
{
MessageBox.Show(String.Format("出现问题 " + e.Exception.Message));
} } private void Form1_Load(object sender, EventArgs e)
{ } private void btnStart_Click(object sender, RoutedEventArgs e)
{ StartRecording();
} } public class WaveInfo :INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged; private float _heigth; public float heigth
{
get {
return _heigth;
}
set { if (value != _heigth)
{ _heigth = value;
OnPropertyChanged("heigth");
}
} } private string text;
public string Text
{
get { return text; }
set { text = value; OnPropertyChanged("Text"); }
} protected void OnPropertyChanged(string propertyName = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
} } } <Window x:Class="TestAudioWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid> <Button x:Name="btnStart" Click="btnStart_Click" Content="btnStart" HorizontalAlignment="Left" Margin="145,20,0,0" VerticalAlignment="Top" Width="169" Height="37"/>
<ListView BorderThickness="0" Name="listView" DataContext="sampleAggregator" Height="232" VerticalAlignment="Bottom"> <ListView.ItemTemplate>
<DataTemplate>
<Label Margin="0" Padding="0" Background="Pink" Width="2" Height="{Binding heigth}"></Label>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Disabled" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel> </ListView> <WrapPanel ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Disabled" Orientation="Horizontal" Height="70" VerticalAlignment="Bottom">
<Label Margin="0" Padding="0" Background="Pink" Width="2" Height="22"></Label>
<Label Margin="0" Padding="0" Background="Pink" Width="2" Height="33"></Label>
<Label Margin="0" Padding="0" Background="Pink" Width="2" Height="44"></Label> </WrapPanel> </Grid>
</Window>

  

参考:

https://channel9.msdn.com/coding4fun/articles/AutotuneNET

https://github.com/markheath/voicerecorder

http://www.codesoso.com/code/Curve_RealTime.aspx

C# NAudio 录制声音和显示波形图的更多相关文章

  1. Android使用的开发MediaRecorder录制声音

    至 Android 录制声音的应用,Android提供 MediaRecorder 类别.大约MediaRecorder可以参考一个特定的解释<Android开发之MediaRecorder类具 ...

  2. Microsoft Web Test Recorder在录制时没有显示

    在进行web test录制时,IE启动后,在左侧可能没有显示Microsoft Web Test Recorder,这很有可能是因为IE加载项中,该项被禁止了,按照如下操作可解决此问题: 1. 打开I ...

  3. 电脑没有声音,显示“未插入耳机或扬声器”,检测不到Realtek高清晰音频管理器

    2018-7-16,电脑彻夜未关,早上发现已经死机了.关机重启之后,就发现没有声音了,提示“未插入耳机或扬声器”,并且检测不到Realtek高清晰音频管理器,只能检查到显卡音频输出.首先,音箱在其他电 ...

  4. Android上使用MP3格式录制声音

    0. 下载LAME 并解压缩 http://lame.sourceforge.net/download.php http://sourceforge.net/projects/lame/files/l ...

  5. NI CWGraph 显示波形图

    ptrWaveBox.Axes(1).Maximum = 1000 ptrWaveBox.Axes(2).Maximum = 20 ptrWaveBox.Axes(2).Minimum = 0 Dim ...

  6. android中使用MediaRecoder录制声音

    package com.test.mediarecorder; import java.io.File; import android.media.MediaRecorder; import andr ...

  7. C# NAudio录音和播放音频文件-实时绘制音频波形图(从音频流数据获取,而非设备获取)

    NAudio的录音和播放录音都有对应的类,我在使用Wav格式进行录音和播放录音时使用的类时WaveIn和WaveOut,这两个类是对功能的回调和一些事件触发. 在WaveIn和WaveOut之外还有对 ...

  8. 使用MediaRecorder录制视频短片

    MediaRecorder除了可用于录制音频之外,还可用于录制视频,使用MediaRecorder录制视频与录制音频的步骤基本相同.只是录制视频时不仅需要采集声音,还需要采集图像.为了让MediaRe ...

  9. Android使用的开发MediaRecorder录制视频

    MediaRecorder除了使用录制音频.还可用于录制视频.关于MediaRecorder的具体解释大家能够參考<Android开发之MediaRecorder类具体解释>.使用Medi ...

随机推荐

  1. docker下进去mysql 编写语句

    设置密码可使用 docker exec -it mysql01 bash        --mysql01:数据库名字 mysql -u root -p ALTER USER 'root'@'%' I ...

  2. cassandra查询效率探讨

    cassandra目前提倡的建表与查询方式为CQL方式,传统的cassandra-cli相关的api由于性能问题将逐步淘汰,而cassandra-cli也将在2.2版本之后被淘汰. 在CQL中,可以利 ...

  3. oracle 使用问题

    12541: 典型的listener.ora 文件内容: SID_LIST_LISTENER =   (注册到监听器的service name所在区域)  (SID_LIST =    (SID_DE ...

  4. vm安装ubantu的详细过程(转载)

    这里转载一个非常实用的vm虚拟机安装linux系统的文章有需要的可以看下面链接: https://blog.csdn.net/u013142781/article/details/50529030

  5. Linux中断流程分析

    裸机中断: 1.中断流入口 2.事先注册中断处理程序 3.根据中断源编号,调取处理程序 irq_svc:1.等到产生中断源的编号(每一个中断号都有一个描述结构) 2.

  6. 10 Zabbix4.4.1系统告警“Zabbix server is not running”

    点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 Zabbix4.4.1系统告警“Zabbix server is not running” 第一步 ...

  7. 08 自学Aruba之限制应用流量

    点击返回:自学Aruba之路点击返回:自学Aruba集锦 08 自学Aruba之限制应用流量 限制带宽请查阅:点击 下文描述的步骤,主要是针对某一个SSID所用用户在使用某一个应用的时候设置共享带宽. ...

  8. Mac下的LDAP客户端 ApacheDirectoryStudio

    mac下的ldap browser,最开始下载的最新版本的 地址 http://directory.apache.org/studio/downloads.html 使用的时候经常卡死,尝试下载老版本 ...

  9. Efficient Estimation of Word Representations in Vector Space (2013)论文要点

    论文链接:https://arxiv.org/pdf/1301.3781.pdf 参考: A Neural Probabilistic Language Model (2003)论文要点  https ...

  10. win10上使用自带的Hyper-V安装虚拟机

    Hyper-V管理器,新建虚拟机,安装了.iso系统,但启动报错,电脑上联想G40-70,都说在bios设置的security里开启硬件虚拟化选项,可我security里没有虚拟化相关选项, 后来在 ...