C# NAudio 录制声音和显示波形图
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 录制声音和显示波形图的更多相关文章
- Android使用的开发MediaRecorder录制声音
至 Android 录制声音的应用,Android提供 MediaRecorder 类别.大约MediaRecorder可以参考一个特定的解释<Android开发之MediaRecorder类具 ...
- Microsoft Web Test Recorder在录制时没有显示
在进行web test录制时,IE启动后,在左侧可能没有显示Microsoft Web Test Recorder,这很有可能是因为IE加载项中,该项被禁止了,按照如下操作可解决此问题: 1. 打开I ...
- 电脑没有声音,显示“未插入耳机或扬声器”,检测不到Realtek高清晰音频管理器
2018-7-16,电脑彻夜未关,早上发现已经死机了.关机重启之后,就发现没有声音了,提示“未插入耳机或扬声器”,并且检测不到Realtek高清晰音频管理器,只能检查到显卡音频输出.首先,音箱在其他电 ...
- Android上使用MP3格式录制声音
0. 下载LAME 并解压缩 http://lame.sourceforge.net/download.php http://sourceforge.net/projects/lame/files/l ...
- NI CWGraph 显示波形图
ptrWaveBox.Axes(1).Maximum = 1000 ptrWaveBox.Axes(2).Maximum = 20 ptrWaveBox.Axes(2).Minimum = 0 Dim ...
- android中使用MediaRecoder录制声音
package com.test.mediarecorder; import java.io.File; import android.media.MediaRecorder; import andr ...
- C# NAudio录音和播放音频文件-实时绘制音频波形图(从音频流数据获取,而非设备获取)
NAudio的录音和播放录音都有对应的类,我在使用Wav格式进行录音和播放录音时使用的类时WaveIn和WaveOut,这两个类是对功能的回调和一些事件触发. 在WaveIn和WaveOut之外还有对 ...
- 使用MediaRecorder录制视频短片
MediaRecorder除了可用于录制音频之外,还可用于录制视频,使用MediaRecorder录制视频与录制音频的步骤基本相同.只是录制视频时不仅需要采集声音,还需要采集图像.为了让MediaRe ...
- Android使用的开发MediaRecorder录制视频
MediaRecorder除了使用录制音频.还可用于录制视频.关于MediaRecorder的具体解释大家能够參考<Android开发之MediaRecorder类具体解释>.使用Medi ...
随机推荐
- int 问号的使用
单问号---为泛型 Nullable<int> 的简写方式. 双问号---用于判断前一个操作数是否为null,如为null则"返回"后一个操作数,否则"返回& ...
- 红色警戒2CE修改教程
在大学的时候特别喜欢玩游戏,尤其偏爱单机游戏.在玩一些单机游戏的时候,特意使用了一些修改工具.本来是打算做成一个系列的,但是现在由于时间问题,仅介绍一些.(大概包括rimworld,饥荒,放逐之城,缺 ...
- python、第四篇:记录相关操作
一 介绍 MySQL数据操作: DML ======================================================== 在MySQL管理软件中,可以通过SQL语句中的 ...
- Mac OSX编译安装php5.6
安装好OSX 10.13以后默认自带的php7.1.7,跟现有环境不兼容,所以准备编译安装php5.6,自带的php7不建议卸载,重新安装一份php5.6 1.安装php的一些依赖,推荐使用brew安 ...
- Kruskal重构树+LCA || BZOJ 3732: Network
题面:https://www.lydsy.com/JudgeOnline/problem.php?id=3732 题解:Kruskal重构树板子 代码: #include<cstdio> ...
- POJ1059Glass Beads
Once upon a time there was a famous actress. As you may expect, she played mostly Antique Comedies m ...
- 结束&新的开始。
我退役啦. 真的很抱歉,但我的学习周期还是太长了,没能在noi之前让自己变得足够强啊. FareWellOi.虽然很舍不得,但总要告别对吧. 相比竞赛的跳跃性钻研性学习,我的优势在于系统性学习.所以我 ...
- nginx防止跳转到内网解决
proxy_redirect http://test.abc.com:9080/ /;
- Puppet部署:安装puppet server、client
Puppet部署:安装puppet server.client puppet与其他手工操作工具有一个最大的区别就是 puppet的配置具有稳定性,因此你可以多次执行puppet,一旦你更新了你的配 ...
- LOJ-6283-数列分块7
链接: https://loj.ac/problem/6283 题意: 给出一个长为 的数列,以及 个操作,操作涉及区间乘法,区间加法,单点询问. 思路: 考虑整块的乘法, 同时对整块的add标记也要 ...