Quantcast
Channel: NAudio
Viewing all 5831 articles
Browse latest View live

New Post: My program gets very slow to respond/stuck while fft is calculated


New Post: How to show the MIDI note name when the note is playing?

$
0
0
I'm using MIDI toolkit

This is what i've done so far. I know it's wrong. :(
for (int i = 0; i < file.Events.Count(); i++) {
     
foreach (MidiEvent note in file.Events[i])
 
try{
      if (note.CommandCode == MidiCommandCode.NoteOn){
                  var n = (NoteOnEvent)note;
                  var off = n.OffEvent;
                  Debug.WriteLine(off.NoteNumber);
                  Debug.WriteLine(off.NoteName);

                  lblNote.Content = off.NoteName.ToString();                                              
        }

      }
         catch (Exception ex) { }
                                           
  }

New Post: How to show the MIDI note name when the note is playing?

$
0
0
OK that's not part of NAudio. I don't know how you'd know where it was up to in the file

New Post: How to show the MIDI note name when the note is playing?

$
0
0
You meant the sample i've shown above? I did like this which is wrong because it reads the file when the file is loaded not while playing ..

Reviewed: NAudio 1.7.3 (Oct 14, 2016)

$
0
0
Rated 5 Stars (out of 5) - They're awesome!

New Post: How to show the MIDI note name when the note is playing?

$
0
0
What I mean is that NAudio doesn't play MIDI files, so you must be using something else to play them. So there isn't an easy way to know which note is currently playing.

New Post: Synchronizing play starting time with PC clock

$
0
0
sorry for long delay replying. What I'd do is feed a WaveOutEvent (or similar) with a custom SampleProvider. Then in the Read method keep track of exactly how many samples so far have been read and start returning audio from your source file at the exact right moment. You could possibly make something like this by combining a MixingSampleProvider with an OffsetSampleProvider

New Post: how to plot fft results in realtime from a mic and get a stable and accurate spectrum

$
0
0
Hello,
Im a little bit new to audio processing
Im trying to record a 17khz pitch using the laptop built in mic and then plot the spectrum graph and see how it changes through the whole spectrum, I used the naudio library, first I created a wavein to record the sound then added the samples from the buffer to the sampleaggregator function to return the fft values so that I can plot them. the graph gives correct results but its not too stable and its hard to know what the right frequency is as the magnitude keeps changing to high and low very fast. and also why when there is some noise in the background the 17khz pitch is not detected by the fft or has very small magnitude which cant be recognized even though the noise is usually voice which is far from 17khz.

I tried an application that shows the frequency spectrum and had no issues so the problem is not from the microphone

Im using a sample rate of 44100 and a fftlength of 4096
this is the main with button when pressed it starts recording
private void B1_Click(object sender, EventArgs e)
        {
             recorder = new WaveIn();
            recorder.DeviceNumber = 0;
            recorder.BufferMilliseconds = 50;
            recorder.WaveFormat = new WaveFormat(samplerate,32, 1);
            recorder.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);

            recorder.StartRecording();

             //fft
            sampleAggregator.FftCalculated += new EventHandler<FftEventArgs>(FftCalculated);
            sampleAggregator.PerformFFT = true;

               //chart graph
            chart1.Series["wave"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine;
                chart1.Series["wave"].ChartArea = "ChartArea1";
        }

private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
        {
         
        byte[] buffer = e.Buffer;
        int bytesRecorded = e.BytesRecorded;
        int bufferIncrement = recorder.WaveFormat.BlockAlign;        
        for (int index = 0; index < bytesRecorded; index +=bufferIncrement)
            {
                float sample = Convert.ToSingle(buffer[index] + buffer[index + 1] + buffer[index + 2] + buffer[index + 3]);
                sampleAggregator.Add(sample);
            }
        }

void FftCalculated(object sender, FftEventArgs e)
        {
            chart1.Series["wave"].Points.Clear();
            int len= e.Result.Length;
            double ampl;
              for (int i = Freq2Index(15000, samplerate, fftLength); i < Freq2Index(21000, samplerate,fftLength); i++)
            {

                ampl = Math.Sqrt((e.Result[i].X * e.Result[i].X) + (e.Result[i].Y * e.Result[i].Y));
                 chart1.Series["wave"].Points.AddXY((int)Index2Freq(i, samplerate, fftLength), ampl);
            }
        }
and this the sampleaggregator class
using NAudio.Dsp; // The Complex and FFT are here!

class SampleAggregator
{
    // FFT
    public event System.EventHandler<FftEventArgs> FftCalculated;
    public bool PerformFFT { get; set; }

    // This Complex is NAudio's own! 
    private Complex[] fftBuffer;
    private FftEventArgs fftArgs;
    private int fftPos;
    private int fftLength;
    private int m;

    public SampleAggregator(int fftLength)
    {
        if (!IsPowerOfTwo(fftLength))
        {
            throw new System.ArgumentException("FFT Length must be a power of two");
        }
        this.m = (int)System.Math.Log(fftLength, 2.0);
        this.fftLength = fftLength;
        this.fftBuffer = new Complex[fftLength];
        this.fftArgs = new FftEventArgs(fftBuffer);
    }

    bool IsPowerOfTwo(int x)
    {
        return (x & (x - 1)) == 0;
    }

    public void Add(float value)
    {
        if (PerformFFT && FftCalculated != null)
        {
            // Remember the window function! There are many others as well.
            fftBuffer[fftPos].X = (float)(value * FastFourierTransform.HammingWindow(fftPos, fftLength));
            fftBuffer[fftPos].Y = 0; // This is always zero with audio.
            fftPos++;
            if (fftPos >= fftLength)
            {
                fftPos = 0;
                FastFourierTransform.FFT(true, m, fftBuffer);
                FftCalculated(this, fftArgs);
            }
        }
    }
}

public class FftEventArgs : System.EventArgs
{
    public FftEventArgs(Complex[] result)
    {
        this.Result = result;
    }
    public Complex[] Result { get; private set; }
}
what can i do to get more stable and accurate measures from the fft function and also not affected by any other frequencies.

can you help or give any suggestion that i can use that can make it better.
and thank you very much

New Post: how to plot fft results in realtime from a mic and get a stable and accurate spectrum

$
0
0
for starters, your method of getting the floating point samples is flawed. You can't add together the four byte values. Also, you're not recording IEEE float, but 32 bit integer samples. So you'd need to use BitConverter.ToInt32 on every four bytes. I'd record at 16 bit, use BitConverter.ToInt16 and then divide by 32768f to turn it into a floating point sample.

New Post: how to plot fft results in realtime from a mic and get a stable and accurate spectrum

$
0
0
Thank you very much mark, I have been looking for an answer for a couple of days now and didnt know what was the problem. I tried your solution and now it works great .
The signal is stable and its not affected by noise.
I really appreciate your help

New Post: Can NAudio do audio Quantization?

$
0
0
Very interesting, I didn't know that, Thanks for the info :)

New Post: How to show the MIDI note name when the note is playing?

$
0
0
I fixed it thanks mark :) yes i'm using midi toolkit. It raises an event called HandleMIDIChannelMessagePlayed through that you can get the midi note which is currently playing. If you have more then one note played in same time, just the last note will be shown.

New Post: Mixing an oscillator with a wav file

$
0
0
Hi,
I'm trying to use a MixingWaveProvider32 to play both wav files and oscillator tones. How should I go about doing this? I have the wav files working but the oscillator is generating a bunch of noise. I'm using something like this for the oscillator. Any help would be much appreciated.

New Post: Mixing an oscillator with a wav file

$
0
0
I can't tell what the issue you're facing is, but you could try using MixingSampleProvider and SignalGenerator which are newer than that blog post and may prove easier to use.

New Post: Mixing an oscillator with a wav file

$
0
0
I got it working using those newer classes. Thanks!

New Post: Group chat

$
0
0
How could i make the Network chat demo use chat rooms or group chat? I know how to handle room assignment on my end and everything, but how would I tell naudio demo to only send voice to that particular room?

New Post: Group chat

$
0
0
well NAudio's focus is purely on capturing and playing audio. It's up to you how you transmit it over the network and it depends how your system is architected, Either you'd send UDP packets containing audio to different ports or IP addresses depending on the group, or you'd create a payload that includes the target group id and the audio data

New Post: Audio file shorter than should be. Any Ideas?

$
0
0
My program takes multiple line in inputs and writes them to seperate files. Split in 1 hour pices.
When I have 2 sorces 1st writes good and loses in worst way 1 sec from audio, but 2nd file loses around 15 or more sec. Any ideas why?

My timer tick code:

{
foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            row.Cells[1].Value = ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00");               
        }          

        if (lastHour < DateTime.Now.Hour|| (lastHour == 59 && DateTime.Now.Hour == 0))
        {
            lastHour = DateTime.Now.Houre;

            foreach (var line in configList)
            {
                colection[line.Column1].StopRecord();
            }

            timeCounter.Stop();
            timeCounter.Reset();

            foreach (var line in configList)
            {
                timeCounter.Start();
                if (!Directory.Exists(line.Column2)) { Directory.CreateDirectory(line.Column2); }
                colection[line.Column1].StartRecord(line.Column4, line.Column2 + line.Column1 + DateTime.Now.ToString("_yyyy_MM_dd_HHmmss_fff") + ".wav");
            }
        }       
}

New Post: Audio file shorter than should be. Any Ideas?

$
0
0
I can't really understand how your program works from that code. But if I was doing this, I would keep track of exactly how many bytes of audio I'd written to a file, so I could know exactly when I had written an hour to the file. That will be much more accurate than checking DateTime.Now.

Commented Unassigned: Dictation recorder hangs on waveInClose [16501]

$
0
0
Our dictation software hangs on NAudio call as described below. This has been tried to get fixed for ages but no luck. Hope you can help!


Hang happens in WaveIn.cs in CloseWaveInDevice() function, line 336 WaveInterop.waveInClose(waveInHandle), that row is in bold below.

private void CloseWaveInDevice()
{

if (waveInHandle == IntPtr.Zero) return;
_logger.Log(LogLevel.Debug, () => "close wavein");

MmException.Try(WaveInterop.waveInStop(waveInHandle), "waveInStop");

MmException.Try(WaveInterop.waveInReset(waveInHandle), "waveInReset");

if (buffers != null)
{
_logger.Log(LogLevel.Debug, () => "close wavein, buffers=" + buffers.Length.ToString());
for (int n = 0; n < buffers.Length; n++)
{
_logger.Log(LogLevel.Debug, () => "buffers[" + n + "] dispose call");
buffers[n].Dispose();
_logger.Log(LogLevel.Debug, () => "buffers[" + n + "] disposed");
}
buffers = null;
}
_logger.Log(LogLevel.Debug, () => "buffers disposed, try to close waveIn");
var result = WaveInterop.waveInClose(waveInHandle);
_logger.Log(LogLevel.Debug, () => "waveInClose result: " + result.ToString());

waveInHandle = IntPtr.Zero;
// _logger.Log(LogLevel.Debug, () => "close wavein method end");
}


WaveInClose is called every time recording is paused to control recording led on Olympus DR-2X00 mic.

waveInClose is from winmm library ->
[DllImport("winmm.dll")]
public static extern MmResult waveInClose(IntPtr hWaveIn);

msdn -> https://msdn.microsoft.com/en-us/library/dd743840(v=vs.85).aspx

Problem is that it doesn't return error code -> it just never returns from this function in this case.

attached is a debug log from the software. It hangs on the last row.

-Juha

Comments: Hi, thanks for the suggestion! Please specify what do you mean by "when are you calling this". What would be needed besides code snippet abowe? Recording really should be finished before disposing even tried it now with slight delay before dispose, no change.
Viewing all 5831 articles
Browse latest View live