要确定C#中.wav文件的长度(即持续时间),可以使用以下方法:
以下是一个简单的C#代码示例,用于确定.wav文件的长度:
using System;
using System.IO;
public static TimeSpan GetWavFileDuration(string fileName)
{
using (var fileStream = File.OpenRead(fileName))
{
using (var binaryReader = new BinaryReader(fileStream))
{
// 跳过RIFF标签
binaryReader.ReadBytes(4);
// 跳过文件大小
binaryReader.ReadBytes(4);
// 跳过WAVE标签
binaryReader.ReadBytes(4);
// 跳过fmt标签
binaryReader.ReadBytes(4);
// 读取数据大小
int dataSize = binaryReader.ReadInt32();
// 跳过其他格式信息
binaryReader.ReadBytes(16);
// 读取采样率
int sampleRate = binaryReader.ReadInt32();
// 跳过其他信息
binaryReader.ReadBytes(6);
// 读取采样位数
short bitsPerSample = binaryReader.ReadInt16();
// 计算音频长度
double duration = (double)dataSize / (sampleRate * bitsPerSample / 8);
return TimeSpan.FromSeconds(duration);
}
}
}
使用此方法,可以轻松地确定.wav文件的长度。请注意,此示例仅适用于无损的.wav文件,并且假定.wav文件的格式正确。
领取专属 10元无门槛券
手把手带您无忧上云