【发布时间】:2014-06-29 13:46:44
【问题描述】:
所以我试图读取 .wav 文件的幅度数据以便稍后在 DFT 中使用它,我使用此代码在 C# 中获取幅度数据并将其放入 .txt 文件中
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
namespace SoundToAmplitudes
{
class Program
{
private static int Main(string[] args)
{
#if DEBUG
Console.WriteLine(String.Join(", ", args));
args = new[] { @"C:\Users\s550c\Documents\visual studio 2010\Projects\DFT\DFT\newrecord.wav" };
#endif
return Cli(args);
}
static int Cli(string[] args)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\test6.txt");
string fileName = args[0];
var soundFile = new FileInfo(fileName);
foreach (float s in AmplitudesFromFile(soundFile))
{
Console.WriteLine(s);
file.WriteLine(s);
}
file.Close();
//Console.WriteLine();
#if DEBUG
Console.Read();
#endif
return 0;
}
public static IEnumerable<float> AmplitudesFromFile(FileInfo soundFile)
{
var reader = new AudioFileReader(soundFile.FullName);
int count = 4096; // arbitrary
float[] buffer = new float[count];
int offset = 0;
int numRead = 0;
while ((numRead = reader.Read(buffer, offset, count)) > 0)
{
foreach (float amp in buffer.Take(numRead))
{
yield return amp;
}
}
}
}
}
该程序为我提供了一个大约 1 秒的声音文件的一长串数据(准确地说是 145920 个数据),所以我的问题是:
每个数据之间的时间间隔是多少? (比如 1^-10 秒还是 smt?),我怎么知道?
如果我想自己设置每个数据之间的间隔,我应该如何更改代码?
【问题讨论】:
-
我没有关注。为什么要将波形文件样本视为浮点数?假设您正在尝试打开未压缩的 PCM 文件,则缓冲区应该是 short int 类型。好像您只是找到了一些代码并且不知道如何使用它。您知道标题中有多少样本。我认为您的 AudioFileReader 应该已加载此类信息。
-
是的,比如我把间隔设置为0.01秒,那么我得到的数据就是0秒的幅度; 0.01 秒; 0.02 秒,以此类推。
-
@Tarec 是的,就像我说我以前从未玩过音频文件,所以我完全不知道这些东西是如何工作的。而且我不能把它改短,因为 NAudio 库中的函数 AudioFileReader.Read 需要 float