C#将录音数据文件保存为wav格式文件,这里使用到的是WavHelper工具类。

WavHelper工具类:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace WavHelperTool
{
/// <summary>
/// 生成wav文件的帮助类,本类来自网络,作者不详
/// </summary>
public class WavHelper : IDisposable
{
#region 变量
private MyWaveFormat mWavFormat;
private int mSampleCount = 0;
private string mFileName = "";
private FileStream mWaveFile = null;
private BinaryWriter mWriter = null;
private int _sampleRate = 0;
private short _channels = 0;
private string _filePath = "";
#endregion public WavHelper(string audioFileName, int sampleRate, short channels)
{
_filePath = audioFileName;
_sampleRate = sampleRate;
_channels = channels;
this.mFileName = audioFileName;
mWavFormat = new MyWaveFormat();
mWavFormat.SamplesPerSecond = _sampleRate;
mWavFormat.BitsPerSample = 16;
mWavFormat.Channels = _channels;
mWavFormat.BlockAlign = (short)(mWavFormat.Channels * (mWavFormat.BitsPerSample / 8));
mWavFormat.AverageBytesPerSecond = mWavFormat.BlockAlign * mWavFormat.SamplesPerSecond;
Start();
} /// <summary>
/// 存放的录音文件路径
/// </summary>
public string FilePath
{
get { return _filePath; }
} public void Dispose()
{
Stop();
} /// <summary>
/// 结束写入并关闭文件
/// </summary>
private void Stop()
{
// 写WAV文件尾
mWriter.Seek(4, SeekOrigin.Begin);
mWriter.Write((int)(mSampleCount + 36));
mWriter.Seek(40, SeekOrigin.Begin);
mWriter.Write(mSampleCount); mWriter.Close();
mWaveFile.Close();
mWriter = null;
mWaveFile = null;
} /// <summary>
/// 创建保存的波形文件,并写入必要的文件头.
/// </summary>
private void Start()
{
// Open up the wave file for writing.
mWaveFile = new FileStream(mFileName, FileMode.Create);
mWriter = new BinaryWriter(mWaveFile);
/**************************************************************************
Here is where the file will be created. A
wave file is a RIFF file, which has chunks
of data that describe what the file contains.
A wave RIFF file is put together like this:
The 12 byte RIFF chunk is constructed like this:
Bytes 0 - 3 : 'R' 'I' 'F' 'F'
Bytes 4 - 7 : Length of file, minus the first 8 bytes of the RIFF description.
(4 bytes for "WAVE" + 24 bytes for format chunk length +
8 bytes for data chunk description + actual sample data size.)
Bytes 8 - 11: 'W' 'A' 'V' 'E'
The 24 byte FORMAT chunk is constructed like this:
Bytes 0 - 3 : 'f' 'm' 't' ' '
Bytes 4 - 7 : The format chunk length. This is always 16.
Bytes 8 - 9 : File padding. Always 1.
Bytes 10- 11: Number of channels. Either 1 for mono, or 2 for stereo.
Bytes 12- 15: Sample rate.
Bytes 16- 19: Number of bytes per second.
Bytes 20- 21: Bytes per sample. 1 for 8 bit mono, 2 for 8 bit stereo or 16 bit mono, 4 for 16 bit stereo.
Bytes 22- 23: Number of bits per sample.
The DATA chunk is constructed like this:
Bytes 0 - 3 : 'd' 'a' 't' 'a'
Bytes 4 - 7 : Length of data, in bytes.
Bytes 8 -: Actual sample data.
***************************************************************************/
// Set up file with RIFF chunk info.
char[] ChunkRiff = { 'R', 'I', 'F', 'F' };
char[] ChunkType = { 'W', 'A', 'V', 'E' };
char[] ChunkFmt = { 'f', 'm', 't', ' ' };
char[] ChunkData = { 'd', 'a', 't', 'a' }; short shPad = 1; // File padding
int nFormatChunkLength = 0x10; // Format chunk length.
int nLength = 0; // File length, minus first 8 bytes of RIFF description. This will be filled in later.
short shBytesPerSample = 0; // Bytes per sample. // 一个样本点的字节数目
if (8 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels)
shBytesPerSample = 1;
else if ((8 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels) || (16 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels))
shBytesPerSample = 2;
else if (16 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels)
shBytesPerSample = 4; // RIFF 块
mWriter.Write(ChunkRiff);
mWriter.Write(nLength);
mWriter.Write(ChunkType); // WAVE块
mWriter.Write(ChunkFmt);
mWriter.Write(nFormatChunkLength);
mWriter.Write(shPad);
mWriter.Write(mWavFormat.Channels);
mWriter.Write(mWavFormat.SamplesPerSecond);
mWriter.Write(mWavFormat.AverageBytesPerSecond);
mWriter.Write(shBytesPerSample);
mWriter.Write(mWavFormat.BitsPerSample); // 数据块
mWriter.Write(ChunkData);
mWriter.Write((int)0); // The sample length will be written in later.
} /// <summary>
/// 每当采集到音频数据时,将其写入
/// </summary>
/// <param name="data"></param>
public void WriteAudioData(byte[] data)
{
mWriter.Write(data, 0, data.Length);
mSampleCount += data.Length;
}
} public class MyWaveFormat
{
/// <summary>
/// 采样率
/// </summary>
public int SamplesPerSecond; /// <summary>
/// 采样位数
/// </summary>
public short BitsPerSample; /// <summary>
/// 通道数
/// </summary>
public short Channels; /// <summary>
/// 单位采样点的字节数
/// </summary>
public short BlockAlign; /// <summary>
/// 每秒平均码率
/// </summary>
public int AverageBytesPerSecond;
}
}

C#保存调用:

//1、定义wav文件生成类
private WavHelper microphoneWav = null; //2、初始化麦克风数据wav文件写入器
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "microphone.wav");//根目录下生成microphone.wav
microphoneWav = new WavHelper(path, sampleRate, channelCount);//保存路径、采样率、频道数 //3、数据写入wav文件中
byte[] data = "xxx";//比特数据
microphoneWav.WriteAudioData(data); //4、关闭写入
microphoneWav.Dispose();
microphoneWav = null;

总结:实践是检验真理的唯一标准。

C#中使用WavHelper保存录音数据为wav文件的更多相关文章

  1. pcm数据生成wav文件

    Qt由pcm数据生成wav文件 void AudioGrabber::saveWave(const QString &fileName, const QByteArray &raw, ...

  2. JQuery中使用FormData异步提交数据和提交文件

    web中数据提交事件是常常发生的,但是大多数情况下我们不希望使用html中的form表单提交,因为form表单提交会中断当前浏览器的操作并且会调到另一个地址(即使这个地址是当前页面),并且会重复加载一 ...

  3. Qt由pcm数据生成wav文件

    void AudioGrabber::saveWave(const QString &fileName, const QByteArray &raw, const QAudioForm ...

  4. WAV相关:从PCM16 Little Endian数据转WAV文件

    数据格式 [0.0, -0.0, -0.0, 0.0, 0.0, 0.0, 5.960464477539063e-08, 5.960464477539063e-08, 1.19209289550781 ...

  5. 使用jmeter往指定文件中插入一定数量的数据

    有一个需求,新建一批账号,把获取的账号相关信息存入文本文件,当文本文件保存的数据达到一定的数量,就自动停止新建账号. 分析下需求: 1.把账号信息保存到文件,需要使用bean shell脚本(bean ...

  6. 使用jmeter往指定文件中插入一定数量的数据(转)

    有一个需求,新建一批账号,把获取的账号相关信息存入文本文件,当文本文件保存的数据达到一定的数量,就自动停止新建账号. 分析下需求: 1.把账号信息保存到文件,需要使用bean shell脚本(bean ...

  7. Android中使用speex将PCM录音格式转Wav格式

    Android中使用speex将PCM录音格式转Wav格式 2013-09-17 17:24:00|  分类: android |  标签:android  speex  wav  |举报|字号 订阅 ...

  8. HTML5操作麦克风获取音频数据(WAV)的一些基础技能

    基于HTML5的新特性,操作其实思路很简单. 首先通过navigator获取设备,然后通过设备监听语音数据,进行原始数据采集. 相关的案例比较多,最典型的就是链接:https://developer. ...

  9. html 实体转换为字符:转换 UEditor 编辑器 ( 在 ThinkPHP 3.2.2 中 ) 保存的数据

    在 ThinkPHP 3.2.2 中使用 UEditor 编辑器保存文章内容时,数据库中保存的数据都被转义成实体,例如:&lt;p&gt;&lt;strong&gt;& ...

随机推荐

  1. NOIP 模拟赛 day5 T2 水 故事题解

    题目描述 有一块矩形土地被划分成 \(\small n×m\) 个正方形小块.这些小块高低不平,每一小块都有自己的高度.水流可以由任意一块地流向周围四个方向的四块地中,但是不能直接流入对角相连的小块中 ...

  2. python 12篇 mock接口之flask模块

    一.使用pip install flask按照flask模块. import flask,json # 轻量级web开发框架 server = flask.Flask(__name__) @serve ...

  3. Java Map 集合类在selenium自动化测试设计中的应用

    我们在设计自动化测试用例的时候,往往很多工作是在处理测试的数据. 测试数据无论用Excel 文件, XML文件或者任何一种形式测存储方式,都会设计到参数化以及我们对数据的操作. 这个时候,我们会用到以 ...

  4. Pandas高级教程之:稀疏数据结构

    目录 简介 Spare data的例子 SparseArray SparseDtype Sparse的属性 Sparse的计算 SparseSeries 和 SparseDataFrame 简介 如果 ...

  5. Linux安装Tomcat-Nginx-FastDFS-Redis-Solr-集群——【第九集-补充-热部署项目到tomcat中,但是数据库配置文件错误,中途停止部署,导致执行shutdow.sh报错异常: Could not contact localhost:8005. Tomcat may not be running error while shutting down】

    1,经过千辛万苦的尝试和百度,终于一个博客:http://stackmirror.caup.cn/page/skxugjqj0ldc关于catalina.sh文件的执行引起了我的注意: 2,我执行ca ...

  6. python + flask轻量级框架

    from flask import Flask,jsonify,make_response,abort,Response,request from flask_restful import Api,R ...

  7. Requests方法 -- Blog流程类进行关联

    1.接口封装关联 1.有些接口经常会用到比如登录的接口,这时候我们可以每个接口都封装成一个方法,如:登录.保存草稿.发帖.删帖,这四个接口就可以写成四个方法2.接口封装好了后,后面我们写用例那就直接调 ...

  8. html自定义加载动画

    整体代码 HTML 实现自定义加载动画,话不多说如下代码所示: <!DOCTYPE html> <html lang="en"> <head> ...

  9. 【系统学习ES6】新专题发布

    我要发免费专题了,向下看 公众号和博客都有一阵没更新了,丢了一些粉儿,但是也很庆幸,时时还会有人关注.我并不是什么专业讲师,文章都是利用业余时间手工原创.在这里非常感谢各位的支持和厚爱. 这个月开始, ...

  10. Oracle导入dmp文件:ORACLE错误12899而拒绝行的问题如何解决

    原文链接:https://www.2cto.com/database/201804/736027.html