swharden/FftSharp

Audio sample data

Closed this issue · 1 comments

Hi

I want to use an audio file rather than sample data array. Please advise that how I can use the audio file or convert the audio file to like sample data.

I am trying to use the below code but its not working

public static Double[] audioData(String wavePath)

    {
        Double[] data;
        byte[] wave;
        byte[] sR = new byte[4];
        System.IO.FileStream WaveFile = System.IO.File.OpenRead(wavePath);
        wave = new byte[WaveFile.Length];
        data = new Double[(wave.Length - 44) / 4];//shifting the headers out of the PCM data;
        WaveFile.Read(wave, 0, Convert.ToInt32(WaveFile.Length));//read the wave file into the wave variable
        /***********Converting and PCM accounting***************/
        for (int i = 0; i < data.Length - i * 4; i++)
        {
            data[i] = (BitConverter.ToInt32(wave, (1 + i) * 4)) / 65536.0;
            //65536.0.0=2^n,       n=bits per sample;
        }
       
        return data;
    }

Please provide kind of sample if possible

Thank you
Dhanaji

Hi @dhanajik, this question is related to #30.

Here's the code that shows how to do this from https://github.com/swharden/Spectrogram#read-data-from-a-wav-file

(double[] audio, int sampleRate) ReadWAV(string filePath, double multiplier = 16_000)
{
    using var afr = new NAudio.Wave.AudioFileReader(filePath);
    int sampleRate = afr.WaveFormat.SampleRate;
    int sampleCount = (int)(afr.Length / afr.WaveFormat.BitsPerSample / 8);
    int channelCount = afr.WaveFormat.Channels;
    var audio = new List<double>(sampleCount);
    var buffer = new float[sampleRate * channelCount];
    int samplesRead = 0;
    while ((samplesRead = afr.Read(buffer, 0, buffer.Length)) > 0)
        audio.AddRange(buffer.Take(samplesRead).Select(x => x * multiplier));
    return (audio.ToArray(), sampleRate);
}