C # to read audio files

/// <Summary>
/// WAV file information
/// </ Summary>
public struct WavInfo
{
public String groupId;
public String rifftype;
public Long filesize;
public String ChunkId;
public Long chunkSize;
public Short wFormatTag; // record the code name for this format sound
public ushort wchannels; // number of channels of sound recording.
public ulong dwsamplespersec; // record number of samples per second.
public ulong dwavgbytespersec; // record the amount of data per second.
public ushort wblockalign; // block recording units aligned.
public ushort wbitspersample; // record the number of bits required for each sample.
String datachunkid public;
public Long the datasize;
}


/// <summary>
/// 获取WAV文件信息
/// </summary>
/// <param name="fileName">文件路径</param>
/// <returns></returns>
private WavInfo GetWavInfo(string fileName)
{
WavInfo wavInfo = new WavInfo();
FileInfo fi = new FileInfo(fileName);
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (fs.Length >= 44)
{
byte[] bInfo = new byte[44];
fs.Read(bInfo, 0, 44);
Encoding.Default.GetString(bInfo, 0, 4);
if (Encoding.Default.GetString(bInfo, 0, 4) == "RIFF" && Encoding.Default.GetString(bInfo, 8, 4) == "WAVE" && Encoding.Default.GetString(bInfo, 12, 4) == "fmt ")
{
wavInfo.groupid = Encoding.Default.GetString(bInfo, 0, 4);
System.BitConverter.ToInt32(bInfo, 4);
wavInfo.filesize = System.BitConverter.ToInt32(bInfo, 4);
wavInfo.rifftype = Encoding.Default.GetString(bInfo, 8, 4);
wavInfo.chunkid = Encoding.Default.GetString(bInfo, 12, 4);
wavInfo.chunksize = System.BitConverter.ToInt32(bInfo, 16);
wavInfo.wformattag = System.BitConverter.ToInt16(bInfo, 20);
wavInfo.wchannels = System.BitConverter.ToUInt16(bInfo, 22);
wavInfo.dwsamplespersec = System.BitConverter.ToUInt32(bInfo, 24);
wavInfo.dwavgbytespersec = System.BitConverter.ToUInt32(bInfo, 28);
wavInfo.wblockalign = System.BitConverter.ToUInt16(bInfo, 32);
wavInfo.wbitspersample = System.BitConverter.ToUInt16(bInfo, 34);
wavInfo.datachunkid = Encoding.Default.GetString(bInfo, 36, 4);
wavInfo.datasize = System.BitConverter.ToInt32(bInfo, 40);
}
}
}

return wavInfo;
}


/// <Summary>
/// Get the length of the audio file
/// </ Summary>
/// <param name = "fileName"> File Path </ param>
/// <Returns> return to the unit (s) </ Returns>
Private int GetVoiceDuration (String fileName)
{
int DURATION = 0;
the try
{
wavInfo wavInfo = this.GetWavInfo (fileName);
DURATION = Convert.ToInt32 (wavInfo.datasize / Convert.ToInt64 (wavInfo.dwavgbytespersec));
}
the catch ( EX Exception)
{
. log.error (the StringBuilder new new ( "Get audio file error:") the Append (fileName) .Append the ( ",") .Append the (ex.Message));
}

return duration;
}

 

Guess you like

Origin www.cnblogs.com/jiangyuhu/p/11915284.html