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

New Post: Loud noise at the beginnig and at at the end of a stream with WaveOut.Play()

$
0
0
nothing obviously wrong there, although WaveBuffer is overkill - you can just call Write on the WaveFileWriter and pass buffer in.
You say you are passing sine providers in, so a beep is exactly what you should expect to hear.

New Post: 24 bit to 16 bit on the fly

$
0
0
use BitConverter.GetBytes to turn a float into a byte array

New Post: NAudio 1.7-alpha MediaFoundationReader

New Post: Finding Pattern sound inside another stream

$
0
0
this is an extremely hard problem to solve. You could try using Microsoft's speech recognition API.

New Post: MidiEvent: Get note and channel ID

$
0
0
Hello,

I have two questions:
  1. How can I retrieve the note of a MidiEvent?
  2. How can I get MidiEvents for a specific channel only?
Greetings.

New Post: Record wav from single channel source

$
0
0
Solved.

From ButtonRecord, set the WaveWriter format to mono, then change the WaveIn_DataAvailable as follow:
Private Sub WaveIn_DataAvailable(ByVal sender As System.Object, ByVal e As NAudio.Wave.WaveInEventArgs) Handles WaveIn.DataAvailable
        For i = 0 To e.BytesRecorded / 2 - 1
            e.Buffer(i) = e.Buffer(2 * i)     ' keep the left channel
            ' or, e.Buffer(i)=e.Buffer(2*i+1), to keep the right channel
        Next
        WaveWriter.Write(e.Buffer, 0, e.BytesRecorded / 2)
End Sub

New Post: NAudio and GetPosition() = 105840

$
0
0
Hi,
Sorry for my english...
I've a problem with play any file *.ogg
I using this code:
       long dl;
       using (var vor = new NVorbis.NAudioSupport.VorbisWaveReader(@"D:\voice.ogg"))
       using (var wav = new NAudio.Wave.WaveOut())
       {
                 wav.Init(vor);
                 dl = vor.Length;
                 wav.Play();
                 while (wav.PlaybackState != NAudio.Wave.PlaybackState.Stopped)
                {
                      if (wav.GetPosition() > dl)
                      {
                            wav.Stop();
                       }
                      Thread.Sleep(100);
                 }
        }

if I create consoleapplication - I not have a problem with playing...
if I create wpfapplication, then I have a problem. this object wav.GetPosition() returned value 105840 and not play...

What do I very bad ? ....
Best regards...
Andrzej

New Post: NAudio and GetPosition() = 105840

$
0
0
aboczko:

Looks like your code is running on the same thread as the UI. Try creating a separate thread to run the code above when running under WPF or WinForms.

Also, playback should stop automatically when the end of the stream is reached, so the position check should not be necessary.

Have fun!

New Post: How to read MIDI notes properly

$
0
0
Hello,

I'm trying to read the MIDI notes of one track with 6 channels properly, so I can export it to C++ code which can be read by another device (Arduino).

The first few notes sound right, but at some point it starts sounding weird. The start and end times are being calculated wrong, but I don't know why.

This is the full code, it's not much tho.

This is the MIDI file, which I edited to have 6 channels: http://dev-ch.com/files/818e6e15-8e92-1b1b-1a18-d0d8ffedcf23/piratesofthecarribean.mid

Any help is very welcome!
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using NAudio.Midi;

namespace MidiToCode
{
    public static class Program
    {
        public static void Main()
        {
            foreach (FileInfo midiFile in new DirectoryInfo(Path.Combine(Application.StartupPath, "Input")).GetFiles("*.mid"))
            {
                string name = Path.GetFileNameWithoutExtension(midiFile.Name);

                StreamWriter file = File.CreateText(Path.Combine(Application.StartupPath, "Output", "Song_" + name + ".h"));
                List<string>[] notes = new List<string>[6];

                for (int channel = 0; channel < 6; channel++)
                {
                    notes[channel] = new List<string>();
                    MidiFile midi = new MidiFile(midiFile.FullName);
                    int noteStart = 0, noteEnd = 0, noteNumber = 0;
                    bool recording = false;

                    foreach (MidiEvent note in midi.Events[0])
                    {
                        if (note.Channel - 1 == channel)
                        {
                            if (note.CommandCode == MidiCommandCode.NoteOff)
                            {
                                noteStart = (int)(note.AbsoluteTime - note.DeltaTime);
                                if (noteStart > 65535 || noteEnd > 65535) throw new Exception();
                            }
                            else if (note.CommandCode == MidiCommandCode.NoteOn)
                            {
                                noteEnd = (int)(note.AbsoluteTime - note.DeltaTime);
                                noteNumber = (note as NoteOnEvent).NoteNumber;

                                if (recording)
                                {
                                    notes[channel].Add
                                    (
                                        "\t" +
                                        "0x" + (noteStart >> 8).ToString("x2") + ", " +
                                        "0x" + (noteStart & 0xff).ToString("x2") + ", " +
                                        "0x" + (noteEnd >> 8).ToString("x2") + ", " +
                                        "0x" + (noteEnd & 0xff).ToString("x2") + ", " +
                                        "0x" + noteNumber.ToString("x2") + ","
                                    );
                                }
                                recording = true;
                            }
                        }
                    }
                }

                file.WriteLine("CreateSong(" + name + ")");
                file.WriteLine("{");
                for (int i = 0, count = 24; i < 6; i++)
                {
                    file.WriteLine("\t" +
                        "0x" + (count >> 8).ToString("x2") + ", " +
                        "0x" + (count & 0xff).ToString("x2") + ", " +
                        "0x" + (notes[i].Count >> 8).ToString("x2") + ", " +
                        "0x" + (notes[i].Count & 0xff).ToString("x2") + ",");
                    count += notes[i].Count * 5;
                }
                file.WriteLine();
                for (int i = 0; i < 6; i++)
                {
                    notes[i].ForEach(itm => file.WriteLine(itm));
                }
                file.Write("};");
                file.Close();
            }
        }
    }
}

New Post: IWaveProvider from bytes array

$
0
0
Hi
I need to normalize audio (put volume in [1; -1] interval).

So I used code from Naudio demo, added few lines, and got the following:
using (var reader = new MediaFoundationReader("d:\\Projects\\audio.wma"))
{
    ISampleProvider sp;
    int sourceSamples;
    if (reader.WaveFormat.Encoding == WaveFormatEncoding.Pcm)
    {
        if (reader.WaveFormat.BitsPerSample == 16)
        {
            sp = new Pcm16BitToSampleProvider(reader);
            sourceSamples = (int) (reader.Length/2);
        }
        else if (reader.WaveFormat.BitsPerSample == 24)
        {
            sp = new Pcm24BitToSampleProvider(reader);
            sourceSamples = (int) (reader.Length/3);
        }
        else
        {
            throw new ArgumentException("Currently only 16 or 24 bit PCM samples are supported");
        }
    }
    else if (reader.WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
    {
        sp = new WaveToSampleProvider(reader);
        sourceSamples = (int) (reader.Length/4);
    }
    else
    {
        throw new ArgumentException("Must be PCM or IEEE float");
    }
    sampleData = new float[sourceSamples];
    int n = sp.Read(sampleData, 0, sourceSamples);
}
float maxValue = 0.0f;
float minValue = 0.0f;
for (var i = 1; i < sampleData.Length; i++)
{
    if (sampleData[i] > maxValue)
    {
        maxValue = sampleData[i];
    }
    else if (sampleData[i] < minValue)
    {
        minValue = sampleData[i];
    }
}
var coef1Channel = 1/maxValue;
var coef2Channel = -1/minValue;
for (var i = 1; i < sampleData.Length; i++)
{
    sampleData[i] = sampleData[i] > 0 ? sampleData[i]*coef1Channel : 
                                                          sampleData[i]*coef2Channel;
}
}
so after this audio volume is normalized.
But I have 2 questions:
  1. How can I convert this bytes array back to ISampleProvider or to IWaveProvider?
  2. Is it possible to use MediaFoundationReader from stream instead of file?
Thanks for helping.

New Post: Custom sample provider FFT sample capture issue

$
0
0
Block align would be 4 if you have stereo 16 bit samples, or mono 32 bit samples. In both cases an "audio frame" is four bytes, and it wouldn't make sense to ask for a number of bytes that was not a multiple of four. FFTs operate on multiple samples (you use a power of 2). 1024 samples is common.

New Post: Analyze Music pulses

$
0
0
You should probably start by looking at the NAudio demo code that draws waveforms. This takes short chunks of audio (e.g. 100ms) and finds the highest and lowest sample values during that time.

New Post: NAudio and GetPosition() = 105840

$
0
0
Thank you for your answer.
Also, playback should stop automatically when the end of the stream is reached, so the position check should not be necessary.
I know, but at this moment I want call stop or pause action ...
Looks like your code is running on the same thread as the UI. Try creating a separate thread to run the code above when running under WPF or WinForms.
I think about one, too. But it isn't. When wav.Play(); process skip many bytes and stoped on 105840 (GetPosition()), Any file, .ogg, .wav...

Best regards.

New Post: How to get frequency from a .wav audio file

$
0
0
I want to get frequency and amplitude from wave file using c#. I tried NAudio and FFT, but result is nothing. I am newbie in the programmer, can you help me please.
  private void wavToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Wave File (*.wav)|*.wav;";
            if (open.ShowDialog() != DialogResult.OK) return;

            chart1.Series.Add("wave");
            chart1.Series["wave"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine;
            chart1.Series["wave"].ChartArea = "ChartArea1";

            NAudio.Wave.WaveChannel32 wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(open.FileName));

            byte[] buffer = new byte[8192];
            int read = 0;
            while (wave.Position < wave.Length)
            {
                read = wave.Read(buffer, 0, 8192);

                for (int i = 0; i < read / 4; i++)
                {
                    chart1.Series["wave"].Points.Add(BitConverter.ToSingle(buffer, i * 4));

                }

            }

        }
how advanced code above to get the frequency?

as the example below:

http://naudio.codeplex.com/discussions/440149

output:
bin freq     result.X                     result.Y
0    0kHz = 0.0895436406135559 0
1    2.756kHz = -0.0815449208021164 -0.072540670633316
2    5.512kHz = 0.0273693520575762 0.0248471423983574
3    8.268kHz = 0.000522108399309218 -0.00102939654607326
4   11.024kHz = -0.00428497046232224 -0.00206405459903181
5   13.78kHz = -0.0028145220130682 0.00431088916957378
6   16.536kHz = 0.00255107693374157 -0.00238887779414654
7   19.292kHz = 0.000449806451797485 1.36718153953552E-05

New Post: MidiEvent: Get note and channel ID

$
0
0
Nevermind, I found it out by myself.

New Post: How to read MIDI notes properly

$
0
0
Nevermind, I found it out by myself.

New Post: EnumerateTransforms without MFTEnumEx

$
0
0
Is there a way to write the function EnumerateTransforms in MediaFoundation /MediaFoundationHelpers without using MFTEnumEx in MediaFoundation/MediaFoundationInterop?

New Post: EnumerateTransforms without MFTEnumEx

New Post: NAudio and GetPosition() = 105840

$
0
0
OK, try this:
  • Make vor and wav member variables on your UI class in the codebehind
  • In your "Play" button's click handler instantiate vor and wav, init wav, add a handler for wav.PlaybackStopped, then start playback. Do NOT use a "using" statement.
  • In the PlaybackStopped handler, put your cleanup code (wav.Dispose(); vor.Dispose();)
  • Add a "Stop" button and in its click handler call wav.Stop() if wav is currently playing.
I know this is different than the console code, but it should sidestep any message pumping issues that might be causing the behavior.

One side note: NVorbis is pretty fast, but may not be fast enough to decode in real-time on some slower machines.

Commented Issue: WaveFileChunkReader.ReadWaveHeader assumes that the stream supports position/seek [16354]

$
0
0
I am using this class to read a wave stream but the derived stream class that I am using that contains the wave does not support setting the Postion (CanSeek == false).
public void ReadWaveHeader(Stream stream)
{ ...
while (stream.Position <= stopPosition - 8)
{...
stream.Position += chunkLength; //This line throws an expection.
}
...
}
Is it posible to use another metholody to read the wave that is not based on Postion? or is there another alternative?
Comments: By the way I think that : ``` stream.Position += chunkLength; ``` should really be : ``` stream.Position += ((chunkLength % 2 == 1) ? (chunkLength + 1) : chunkLength); ``` (both occurrences in this file) Given that 1 padding byte sometimes has to be skipped (chunks with an odd "specified" length L, actual length is L + 1 !) Will fix this when ... I understand how to submit a fix on Codeplex !
Viewing all 5831 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>