4

I need a fast method to store all samples of a wav file in an array. I am currently working around this problem by playing the music and storing the values from the Sample Provider, but this is not very elegant.

From the NAudio Demo I have the Audioplayer Class with this Method:

   private ISampleProvider CreateInputStream(string fileName)
    {
        if (fileName.EndsWith(".wav"))
        {
            fileStream = OpenWavStream(fileName);
        }
          throw new InvalidOperationException("Unsupported extension");
        }
        var inputStream = new SampleChannel(fileStream, true);
        var sampleStream = new NotifyingSampleProvider(inputStream);
        SampleRate = sampleStream.WaveFormat.SampleRate;
        sampleStream.Sample += (s, e) => { aggregator.Add(e.Left); }; // at this point the aggregator gets the current sample value, while playing the wav file
        return sampleStream;
    }

I want to skip this progress of getting the sample values while playing the file, instead I want the values immediatly without waiting till the end of the file. Basically like the wavread command in matlab.

  • Because I want to make a STFT from a wav file and I want to calculate it by a button click. For that purpose I need all sample values.. I will try to add some Code and edit my first post – Miguel Rodriguez Mar 14 '13 at 20:50

1 Answers1

1

Use AudioFileReader to read the file. This will automatically convert to IEEE float samples. Then repeatedly call the Read method to read a block of samples into a float[] array.

Mark Heath
  • 48,273
  • 29
  • 137
  • 194
  • 1
    Its working with AudioFileReader.ReadAsync() and a byte array, but I have trouble doing it right with AudioFileReader.Read() and a float array. I always end up with an index out of range exception. I.e I want to store the first 1024 float values in the float array samples: SampleReader.Read(samples, 0, 1024); The next step would be: SampleReader.Read(samples, 1024, 2048); but this step alway crashes.. – Miguel Rodriguez Mar 15 '13 at 11:33
  • usually you keep calling with (samples, 0, 1024). – Mark Heath Mar 15 '13 at 13:07
  • @MiguelRodriguez do you found a solution? – Deim Feb 04 '21 at 14:39