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

Commented Unassigned: NAudio.SoundFont.InfoChunk exception [16476]

$
0
0
NAudio.SoundFont.InfoChunk throws an unnecesary exception if some of the information chunks are missing even though they're optional, makes it harder to load some of the SF2 files.
Comments: I'll be honest, this was a year ago and I'm not entirely sure what I needed this for :( But I'll try to figure it out over the weekend.

Commented Unassigned: NAudio.SoundFont.InfoChunk exception [16476]

$
0
0
NAudio.SoundFont.InfoChunk throws an unnecesary exception if some of the information chunks are missing even though they're optional, makes it harder to load some of the SF2 files.
Comments: sure, sorry was just trying to clean up some old issues

New Post: Help for Exception: NAudio.MmException "UnspecifiedError calling waveOutOpen"

$
0
0
markheath wrote:
Maybe its IEEE float that's causing the issue. You could try opening at 16 bit.
I have tested it with:
public void SetWaveFormat(int sampleRate, int channels)
        {
            //WaveFromat von NAudio
            //Create an new IEEE floating point wave format
            //this.waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels);
            this.waveFormat = WaveFormat.CreateCustomFormat(WaveFormatEncoding.IeeeFloat, sampleRate, channels, 384000, 8, 16);
        }
was that right?
but, the error is also there, also with bitsPerSample = 16 then 32
you'd have to insert a resampler into your pipeline. NAudio has a DMO based resampler you could try.
How can I do that?
In which pipeline?
What is a DMO based resampler?
Background: I just need to create one sine tune and change the frequency programmable. I had done this with DirectX SDK and a C# Audio example for that; a long time earlier. But know DirectX is included into the Microsoft operation system and Audio is now only programmable with C++ project not with a C# project. So I kook for a solution and came to NAudio.

New Post: Help for Exception: NAudio.MmException "UnspecifiedError calling waveOutOpen"

$
0
0
I find a workaround for the problem and a solution: using "DirectSoundOut"

the workaround is a bit stupid but works: I do a "try and catch" and when it crashes I caught the exception, add 1 to the frequency and call WaveOut.Intit() again:

when button is clicked:
       private void btnSineWave_Click(object sender, EventArgs e)
        {
            //There are Audio devices?
            int anzahlAudioDevices = DirectSoundOut.Devices.Count();
            bool bDevice = (anzahlAudioDevices > 0);
            if (!bDevice)
            {
                MessageBox.Show("Kein Audiogerät gefunden!", 
                                this.Text, 
                                MessageBoxButtons.OK, 
                                MessageBoxIcon.Error
                               );
                return; //error: no device for playing any sound
            }

            //ok some found
            StartStopSineWave1(440F);     //Play with DirectSoundOut
            //StartStopSineWave2(440F);    //Play with WaveOut (Error possible)
        }
Workaround for the WaveOut error:
        private void StartStopSineWave2(float frequency)
        {
            if (waveOut == null)
            {
                var sineWaveProvider = new SineWaveProvider32();
                // SetWaveFormat(int SampleRate, int channels)

                int channels = 2; //stereo, =1 ist mono

                //int sampleRate = 16000; 
                int sampleRate = 44100;     //CD-Qualität
                //int sampleRate = 48000;   //Studioqualität
                //int sampleRate = 96000;   //Studioqualität
                if (bNAudioUnspecifiedError) { ++sampleRate; }  //if error in NAudio SampleRate plus 1  - works then.

                /* ERROR: when  sampleRate xx.nnnn kHz == standard-settings of the Realteak Soundcard, 
                        2 channels Stereo CD Qualität
                 -> Exception: NAudio.MmException "UnspecifiedError calling waveOutOpen"
                 came from: 
                 result = WaveInterop.waveOutOpenWindow(out waveOutHandle, 
                                                        (IntPtr)deviceNumber, 
                                                        waveFormat, 
                                                        this.Handle, 
                                                        IntPtr.Zero, 
                                                        WaveInterop.WaveInOutOpenFlags.CallbackWindow
                                                       );


                waveOutHandle is "0" without the handle it crashed (only with Realteak-Audio driver)
                C++ The waveOutOpen function opens the given waveform-audio output device for playback.
                in NAudio [DllImport("winmm.dll")] and call of unamanged code: waveOutOpen(...)
                */

                sineWaveProvider.SetWaveFormat(sampleRate, channels);

                sineWaveProvider.Frequency = frequency;
                sineWaveProvider.Amplitude = 0.25f;

                //WaveOut should be thought of as the default audio output device in NAudio
                waveOut = new WaveOut();

                // –1 indicates the default output device, while 
                // 0 is the first output device(usually the same)
                waveOut.DeviceNumber = -1;
                try
                {
                    waveOut.Init(sineWaveProvider);
                    waveOut.Play();
                }
                catch (MmException mMExp)
                {
                    //if special Realtek-Audio-Card driver error occurse  (Workaround)
                    if (mMExp.Result == MmResult.UnspecifiedError)
                    {
                        sampleRate += 1;
                        sineWaveProvider.SetWaveFormat(sampleRate, channels);
                        try
                        {
                            //nochmal - sollte jetzt gehen
                            waveOut.Init(sineWaveProvider);
                            waveOut.Play();

                            //a flag to do not get into error every time so long the program is running
                            bNAudioUnspecifiedError = true;
                        }
                        catch (Exception exp)
                        {
                            MessageBox.Show("Error: Audiodriver Standard-Einstellungen kollidieren..."
                                            + Environment.NewLine
                                            + exp.Message.ToString()
                                           );
                        }
                    }
                    else
                    {   //all other errors
                        MessageBox.Show("Error in StartStopSineWave():"
                                        + Environment.NewLine
                                        + mMExp.Message.ToString()
                                       );
                        throw;
                    }
                }
            }//eof-if(...)
            else
            {
                waveOut.Stop();

                //If you need to play something else, you should Dispose 
                //of your output device and create a new one.
                waveOut.Dispose();
                waveOut = null;
            }
        }
With DirectSoundOut
      private void StartStopSineWave1(float frequency)
        {
            if (directSoundOut == null)
            {
                var sineWaveProvider = new SineWaveProvider32();

                // Für SetWaveFormat(int SampleRate, int channels)
                int channels = 2; //stereo, =1 ist mono

                //int sampleRate = 16000; 
                int sampleRate = 44100;     //CD-Qualität
                //int sampleRate = 48000;   //Studioqualität
                //int sampleRate = 96000;   //Studioqualität

                sineWaveProvider.SetWaveFormat(sampleRate, channels);

                sineWaveProvider.Frequency = frequency;
                sineWaveProvider.Amplitude = 0.25f;


                directSoundOut = new DirectSoundOut(); //select default device

                try 
                {
                    directSoundOut.Init(sineWaveProvider); //init with source
                    directSoundOut.Play();          //play tune
                }
                catch (Exception exp)
                {   
                    MessageBox.Show("Error in StartStopSineWave():"
                                    + Environment.NewLine
                                    + exp.Message.ToString()
                                   );
                    throw;
                }

            }//eof-if(...)
            else
            {
                directSoundOut.Stop();          //tune playing

                //freeing, releasing, or resetting unmanaged resources.
                directSoundOut.Dispose();       //GC may destroy later (releases the memory)
                directSoundOut = null;           //so it needs to set 'null' for the selection 
            }
        }
I thing that could work for me - thanks a lot for your help! :)

New Post: Help for Exception: NAudio.MmException "UnspecifiedError calling waveOutOpen"

$
0
0
wow, that is weird, but glad you found something that works

New Post: Get audio input channel from mixer NAudio C#

$
0
0
I am very New to NAudio Library and as well as develop audio type of file I have question that how do we get audio input from each channel of Mixer use USB Audio Interface connect to PC (Support ASIO), So this mixer support 8 Channel of Audio Input.

The idea of application is like this
  • when user press on channel 1 button it will get channel 1 input to capture the voice of speaker on that particular channel
  • when user press channel 2 button it will get voice from channel 2 (as separate Channel)
So I just wondering which library class I should use and is there any source code example or best practice for this kind of scenario (I am using C# to Develop)

Thank You

New Post: Getting Total time of file

$
0
0
My application has a list of available files that it can play according to a sequence or a user may manually select and play files. I would like to have the UI show the total playing time for each file and so far the only way I can see to get this is to create a wave provider object, get the Total Time property, and then dispose of the wave provider.

I guess I could keep the wave provider open ready for the user to play it, however there could be many files in a set and this seems overly resource wasteful.

Any other ways of getting this total file time?
Thanks,
Sid

New Post: Getting Total time of file

$
0
0
You could use WinAPi Codepack Shell to request the duration detected by windows

New Post: Writing to WAV after threshold exceeded

$
0
0
Hello,

I am fairly new to using NAudio and I'm currently trying to build a program, that can record for a few seconds after the microphone detects a sound level that exceeds a threshold I've set.

Currently, I'm checking the sound level (Root-mean squared) and writing to a WAV in the WaveIn EventHandler called source_DataAvailable and I have a flag called recordedFlag that is set to false.

Right now there is an 'if' statement that checks if the flag is false and if it is then there will be another 'if' statement inside that checks the RMS. If it exceeds the RMS set, then it will write to a WaveFileWriter object then sets the flag to true.

Since the EventHandler is constantly checking when the microphone is listening, the next time the 'if' statement checks the flag (it will be true), it will display a MessageBox and then dispose the WaveFileWriter, setting it to null and then changing the flag back to false, so the process can repeat.

I'm currently facing a few problems:

1) I can only get the 1 sound that exceeds the RMS (I know with the way I've set things up it only does this, but what I want to be able to write to a WAV for a few seconds instead of writing 1 byte that was recorded, when the threshold exceeds and I do not know how)

2) I want the same WAV file to be overwritten with every successful recording, but I've noticed that there are 3 processor threads, so whenever I've written data to a WAV. There will be 3 different writes to the same waveWriter instance, causing the end WAV to be empty, due to the way I set up the flags
        private void btnRecordEverything_Click(object sender, EventArgs e)
        {
            // Checks to see if any device was selected
            if (lvSource.SelectedItems.Count == 0) return;
 
            // Obtain device number from the index of the first selected item
            int deviceNumber = lvSource.SelectedItems[0].Index;
 
            // Inititalise the source stream
            sourceStream = new NAudio.Wave.WaveIn();
            // Set the device number to the source stream
            sourceStream.DeviceNumber = deviceNumber;
            // Assign a wave format with the standard 44.1kHz and the device number's channel
            sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels);
 
            // source stream will want a new event when there is data available  
            sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(source_DataAvailable);
            // Inititalise WaveWriter
            // Enter file location and make sure the format saved is the same as the source stream
            waveWriter = new NAudio.Wave.WaveFileWriter("aaa.wav", sourceStream.WaveFormat);
 
            sourceStream.StartRecording();
        }
 
        private bool recordedFlag = false;
 
        private void source_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            // Checks if wave writer exists
            if (waveWriter == null)
            {
                waveWriter = new NAudio.Wave.WaveFileWriter("aaa.wav", sourceStream.WaveFormat);
            }
 
            double rms = calculateDBinRMS(e);
 
            string rmsFormatted = string.Format("{0:0.00}", rms); // Just formats the RMS value
 
            int seconds = (int)(waveWriter.Length / waveWriter.WaveFormat.AverageBytesPerSecond); // Calculates the length of the WAV file
 
            rbSoundLevel.AppendText(rmsFormatted + "\n"); // Writes RMS to the rich text box
 
            if (recordedFlag == false)
            {
                if (rms > 800)
                {
                    // Write data to the waveWriter
                    // Data is a byte array
                    // Offset set to 0 to write the whole array of data
                    // Count is the bytes recorded
                    waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
 
                    // Ensure wave file is written by flushing the data out with each write
                    // Prevent RAM from being held
                    waveWriter.Flush();
 
                    recordedFlag = true;
                }
                else
                {
                    MessageBox.Show("Record success!");
                    waveWriter.Dispose();
                    waveWriter = null;
 
                    recordedFlag = false;
                }
            }
        }
Here's the code and a link to the pastebin code

In short, I just want to get my program to start writing to a WAV for a few seconds when the mic picks up an audio level that exceeds the set threshold.

New Post: Writing to WAV after threshold exceeded

$
0
0
you don't seem that far off. Have a flag saying whether you are currently recording or not. In data available - if the flag is not set, check the RMS and if it exceeds the threshold, then set the flag true.

Now, if the flag is true, create the WaveFileWriter if it doesn't already exist and then write the data to the file. If the length of the file is greater than 3 seconds (or whatever) then dispose the wavefilewriter and set the flag back to false.

New Post: Get audio input channel from mixer NAudio C#

$
0
0
The ASIOOut class is probably best for this approach, as its the only one likely to give you access to the 8 input channels. This lets you subscribe to AudioAvailable from which you can access the raw ASIO buffers for best performance, which I'd recommend for your usage.

New Post: Naudio Play Multiple file continuously

$
0
0
To do this, you should make a custom IWaveProvider class whose Read method reads from your first file, and then when that reaches the end, starts reading from the next one and so on.

There is already a class that you could use called ConcatenatingSampleProvider which you could pass a bunch of AudioFileReader instances into. They would all need to have same WaveFormat for this to work

New Post: Playing MP3 file fails silently

$
0
0
Hi all, I am new to NAudio so I apologize in advance for my ignorance. I was testing around just getting an MP3 file to play and I am having a difficult time.

Here is my code:

using NAudio.Wave;
namespace ConsoleApplication2
{
class Program
{
    static void Main(string[] args)
    {
        WaveOutEvent waveOut = new WaveOutEvent();
        WaveStream mp3Reader = new Mp3FileReader("e:\\wonka.mp3");
        waveOut.Init(mp3Reader);
        waveOut.Play();
        mp3Reader.Dispose();
        waveOut.Dispose();
    }
}
}

So when I run that code nothing happens at all but I notice for a split second in the volume mixer the application appears as if it is starting to do something and then it vanishes. I have verified that I can play the file e:\wonka.mp3 in a lot of other ways.

I also had one other question while I am here. Is it possible to pass an audio "file" directly to NAudio from a byte[] rather than writing it to disk first and then passing it to the reader?

New Post: Playing MP3 file fails silently

$
0
0
The Play method just begins playback - it doesn't block until playback stops. So you must pause now until you want to stop or until the PlaybackStopped event is fired.
A simple solution for your app could be to sleep in a loop waiting for the PlaybackState to get set to Stopped.
And Mp3FileReader has a constructor that takes a stream so you could pass in a MemoryStream based on your byte array

New Post: Playing MP3 file fails silently

$
0
0
Is there an async/background way to play the file? Once I get this working in a "basic" way I am going to use NAudio in a WPF application and I can't pause or loop until the file is done playing. Sorry if I misunderstand.

New Post: Playing MP3 file fails silently

$
0
0
well in WPF make the WaveOutEvent and Mp3FileReader a member of your class. Then just call Init and Play and it will play in the background. When the PlaybackStopped event fires, you can clean up.

New Post: Playing MP3 file fails silently

$
0
0
Okay, I am still a little confused as to why the console application won't play the entire file.

I have implemented the PlaybackStopped event and it fires instantly.

What is the correct way to call waveOut.Play() so that it will continue playing until the end of the file?

By the way sorry if I am ignorant I am just following the example here:

https://github.com/naudio/NAudio/wiki/Playing-an-Audio-File

is that example current?

New Post: Playing MP3 file fails silently

$
0
0
Nevermind, I got the example working properly in a WPF application it must just be because I was doing this in a console.

thanks.

New Post: Playing MP3 file fails silently

$
0
0

The problem with your console application is that the file starts playing and then you dispose the object and exit the application before the file is finished playing.

Sid

Sid Price

Desktop Application and Embedded System Design

New Post: Writing to WAV after threshold exceeded

$
0
0
Thanks Mark!! I was able to fix all the issues with the help of your solution :)
Viewing all 5831 articles
Browse latest View live


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