【问题标题】:Reading amplitude data from WAV file at certain interval以一定的间隔从 WAV 文件中读取幅度数据
【发布时间】: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. 每个数据之间的时间间隔是多少? (比如 1^-10 秒还是 smt?),我怎么知道?

  2. 如果我想自己设置每个数据之间的间隔,我应该如何更改代码?

【问题讨论】:

  • 我没有关注。为什么要将波形文件样本视为浮点数?假设您正在尝试打开未压缩的 PCM 文件,则缓冲区应该是 short int 类型。好像您只是找到了一些代码并且不知道如何使用它。您知道标题中有多少样本。我认为您的 AudioFileReader 应该已加载此类信息。
  • 是的,比如我把间隔设置为0.01秒,那么我得到的数据就是0秒的幅度; 0.01 秒; 0.02 秒,以此类推。
  • @Tarec 是的,就像我说我以前从未玩过音频文件,所以我完全不知道这些东西是如何工作的。而且我不能把它改短,因为 NAudio 库中的函数 AudioFileReader.Read 需要 float

标签: c# wav amplitude


【解决方案1】:

回答问题1:数据的区间是由采样率决定的。这可以通过reader.WaveFormat.SampleRate 访问。即每秒的样本数,因此样本之间的时间为 1 / SampleRate。

对于问题 2:我不熟悉 NAudio,所以我不知道它是否有任何功能可以做到这一点,但您可以跳过示例,只获取您想要的示例。

【讨论】:

  • 非常感谢,这对我很有帮助。但是,当我尝试查看我的 wav 文件的采样率时,它是 44100,但程序返回给我 145920 数据,如果它的采样率意味着 44100 数据/秒,它将等于大约 3.3 秒,而我的声音文件只超过1秒,你知道为什么^^?
  • @user3702271:WaveFormat.Channels 指定流中的通道数。可能有两个(单声道文件可能会更改为立体声),在这种情况下,样本是交错的(Left1、Right1、Left2 等)。文件的持续时间将为 1.6 秒。
  • 哦,我明白了!是的,我的 wav 文件确实有 2 个频道,谢谢,这解释了很多 XD
  • @user3702271 在这里您可以找到有关波形文件格式的一些信息,ccrma.stanford.edu/courses/422/projects/WaveFormat
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多