2

What I need to do is calculate the frequency of the microphone input. I'm using IWaveProvider for this and its implemented Read(). The buffer always has a size of 8820 elements and something seems to be going wrong with the conversion from byte array to float array as well (the FloatBuffer property part).

Here are some of the important bits...

This is where I start my recording:

private void InitializeSoundRecording()
{
    WaveIn waveIn = new WaveIn();
    waveIn.DeviceNumber = 0;   
    waveIn.DataAvailable += (s, e) => this.waveIn_DataAvailable(s, e); 
    waveIn.RecordingStopped += (s, e) => this.waveIn_RecordingStopped(s, e);
    waveIn.WaveFormat = new WaveFormat(44100, 1);
    waveIn.StartRecording();
}

When the DataAvailable event handler is called, the following is executed:

private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
    WaveBuffer wb = new WaveBuffer(e.Buffer.Length);

    IWaveProvider iWaveProvider = new PitchDetector(new WaveInProvider(sender as WaveIn), new WaveBuffer(e.Buffer));
    iWaveProvider.Read(wb, 0, e.Buffer.Length);

    PitchDetector pd = iWaveProvider as PitchDetector;

    this.ShowPitch(pd.Pitch);
}

And lastly, this is the "actual" important bit:

private const int FLOAT_BUFFER_SIZE = 8820;
private IWaveProvider source;
private WaveBuffer waveBuffer;
private int sampleRate;
private float[] fftBuffer;
private float[] prevBuffer;
public float Pitch { get; private set; }

public WaveFormat WaveFormat { get { return this.source.WaveFormat; } }

internal PitchDetector(IWaveProvider waveProvider, WaveBuffer waveBuffer = null)
{
    this.source = waveProvider;
    this.sampleRate = waveProvider.WaveFormat.SampleRate;
    this.waveBuffer = waveBuffer;
}

/// <summary>
/// UNSAFE METHOD! 
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private unsafe float[] ByteArrayToFloatArray(byte[] input)
{
    float[] fb = new float[FLOAT_BUFFER_SIZE];
    unsafe
    {
        fixed (byte* ptrBuffer = input)
        {
            float* ptrFloatBuffer = (float*)ptrBuffer;
            for (int i = 0; i < FLOAT_BUFFER_SIZE; i++)
            {
                fb[i] = *ptrFloatBuffer;
                ptrFloatBuffer++;
            }
        }
    }
    return fb;
}

public int Read(byte[] buffer, int offset = 0, int count = 0)
{
    if (this.waveBuffer == null || this.waveBuffer.MaxSize < count)
        this.waveBuffer = new WaveBuffer(count);

    int readBytes = this.source.Read(this.waveBuffer, 0, count);

    if (readBytes > 0) readBytes = count;

    int frames = readBytes / sizeof(float);

    this.Pitch = this.DeterminePitch(this.waveBuffer.FloatBuffer, frames);

    return frames * 4;
}

Strangely enough, when it enters the constructor, waveBuffer contains some data (255, 1, 0, etc.), but when I check the "buffer" parameter of Read(), it's entirely 0. Every element.

Out of curiosity also, why does Read() have a buffer parameter, but isn't actually used in the method at all (I got that piece of code from one of your articles)?

Any help to resolve this issue would be greatly appreciated! I've been at this for quite a while already, but can make no sense out of it.

Thanks, Alain

2
  • one of whose articles?
    – Jodrell
    Apr 8, 2013 at 8:02
  • Pardon me, one of Mark Heath's – from NAudio – articles.
    – Alain
    Apr 8, 2013 at 8:13

2 Answers 2

0

It is not clear what article you are referring to and I am not familiar with this library. However, the Read method is clearly reading in your 'time-series'/or other data. From this, the buffer parameter you speak of is likely to be the padding length that you want to place on either end of your data set.

This padding is known as 'Zero Padding' and it pads your recorded signal with zeros (places n zeros on either end of the signal, where n is set according to the radix used). This allows one to use a longer FFT, which will produce a longer FFT resulting vector.

A longer FFT result has more frequency bins that are more closely spaced in frequency. But they will be essentially providing the same result as a high quality Sinc interpolation of a shorter non-zero-padded FFT of the original data.

This might result in a smoother looking spectrum when plotted without further interpolation.

For further in formation see

https://dsp.stackexchange.com/questions/741/why-should-i-zero-pad-a-signal-before-taking-the-fourier-transform

I hope this helps.

0

This is not really an answer to your question but I wrote a safe generic alternative to your array conversion function.

using System;
using System.Runtime.InteropServices;

public static class Extensions
{
    public staitc TDestination[] Transform<TSource, TDestination>(
        this TSource[] source)
        where TSource : struct
        where TDestination : struct
    {
        if (source.Length == 0)
        {
            return new TDestination[0];
        }

        var sourceSize = Marshal.SizeOf(typeof(TSource));
        var destinationSize = Marshal.SizeOf(typeof(TDestination));

        var byteLength = source.Length * sourceSize;

        int remainder;
        var destinationLength = Math.DivRem(
            byteLength,
            destinationSize,
            out remainder);
        if (remainder > 0)
        {
            destinationLength++;
        }

        var destination = new TDestination[destinationLength];
        Buffer.BlockCopy(source, 0, destination, 0, byteLength);
        return destination;
    }
}

Which obviously, you could use like

var bytes = new byte[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var floats = bytes.Transform<byte, float>();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.