Megazero
Megazero

Reputation: 35

Reading amplitude data from WAV file at certain interval

So I'm trying to read the amplitude data of a .wav file in order to use it in DFT later on, and I use this code to get the amplitude data in C# and put it into a .txt file

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;
                }
            }
        }
    }
}

The program give me a long list of data for a ~1 seconds sound file, (145920 data to be exact), so my questions is this:

  1. What's the time interval between each of those data? (like 1^-10 second or smt?), how do I know it?

  2. If I want to set the interval between each data by myself, how should I change the code?

Upvotes: 0

Views: 1825

Answers (1)

Herman
Herman

Reputation: 2998

In response to question 1: The interval of the data is determined by the sample rate. This can be accessed through reader.WaveFormat.SampleRate. That is the number of samples per second, so the time between the samples is 1 / SampleRate.

For question 2: I am not familiar with NAudio so I do not know if it has any feature do that, but you could skip samples to just get only the samples you want.

Upvotes: 1

Related Questions