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

Edited Unassigned: Wrong DirectSound device GUID [16461]

$
0
0
There are wrong DirectSoundDeviceInfo.Guid and DirectSoundDeviceInfo.ModuleName in NAudio implementation.

List of devices using NAudio (with incorrect Guids)
(_Install-Package NAudio_)
```
foreach (var d in DirectSoundOut.Devices)
{
Console.WriteLine("{0} {1} {2}", d.Description, d.Guid, d.ModuleName);
}
```

List of devices using SlimDX (with correct Guids, I've checked that the same are in Windows registry __HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture__)
(_Install-Package SlimDX_)
```
foreach(DeviceInformation d in DirectSoundCapture.GetDevices())
{
Console.WriteLine("{0} {1} {2}", d.Description, d.ModuleName, d.DriverGuid);
}
```


New Post: Play 3gp File

$
0
0
Hi All,

I am using NAudio in a project that I have built in Android as well. I am trying to make my Windows side able to play .3gp audio that is recorded in the Android version. I have the codecs installed on my computer for .3gp and the files can be played in Windows Media Player but I am getting an error that NAudio is not able to find the codec. Is .3gp not supported at all in NAudio or do I need to do something besides just making sure the necessary codec is installed on the computer?

Thank you,
Erik

Created Unassigned: Memory leak on playback [16462]

$
0
0
I am trying to track down a memory leak when I play lots of mp3 files. If I don't play files, the memory usage is flat, but when I play files, the memory usage slowly climbs.

OS = Windows XP SP3
Application = ASP.NET
NAudio = 1.7

For each file, here is what I use to start the playback:
```
Public Sub PlayFile(ByRef fileName As String) ' play one file
waveOutDevice = New WaveOutEvent()
fReader = New AudioFileReader(fileName)
mainOutputStream = New WaveChannel32(fReader) ' tie the file reader to the output stream
mainOutputStream.PadWithZeroes = False ' need this to detect eof
waveOutDevice.Init(mainOutputStream) ' tie output stream to output device
waveOutDevice.Play()
End Sub
```

and here is the code that I call once the file has finished:
```
Public Sub Cleanup()
If (waveOutDevice IsNot Nothing) Then
If waveOutDevice.PlaybackState <> PlaybackState.Stopped Then
waveOutDevice.Stop() ' stop playing around
End If
End If

If (mainOutputStream IsNot Nothing) Then ' clean up output streams
mainOutputStream.Close()
mainOutputStream.Dispose() ' also disposes the file reader
mainOutputStream = Nothing
End If
If (waveOutDevice IsNot Nothing) Then ' clean up waveout device
waveOutDevice.Dispose()
waveOutDevice = Nothing
End If
End Sub
```
Any advice or directions appreciated.
Jake


Commented Unassigned: Memory leak on playback [16462]

$
0
0
I am trying to track down a memory leak when I play lots of mp3 files. If I don't play files, the memory usage is flat, but when I play files, the memory usage slowly climbs.

OS = Windows XP SP3
Application = ASP.NET
NAudio = 1.7

For each file, here is what I use to start the playback:
```
Public Sub PlayFile(ByRef fileName As String) ' play one file
waveOutDevice = New WaveOutEvent()
fReader = New AudioFileReader(fileName)
mainOutputStream = New WaveChannel32(fReader) ' tie the file reader to the output stream
mainOutputStream.PadWithZeroes = False ' need this to detect eof
waveOutDevice.Init(mainOutputStream) ' tie output stream to output device
waveOutDevice.Play()
End Sub
```

and here is the code that I call once the file has finished:
```
Public Sub Cleanup()
If (waveOutDevice IsNot Nothing) Then
If waveOutDevice.PlaybackState <> PlaybackState.Stopped Then
waveOutDevice.Stop() ' stop playing around
End If
End If

If (mainOutputStream IsNot Nothing) Then ' clean up output streams
mainOutputStream.Close()
mainOutputStream.Dispose() ' also disposes the file reader
mainOutputStream = Nothing
End If
If (waveOutDevice IsNot Nothing) Then ' clean up waveout device
waveOutDevice.Dispose()
waveOutDevice = Nothing
End If
End Sub
```
Any advice or directions appreciated.
Jake


Comments: This is not a memory leak. You can GC.Collect() to free memory by force, or it should be freed anyway automatically in some time.

New Post: Access Violation Exception - 0xc0000005

$
0
0
I get these too actually. I have had this problem for a while but never investigated it. I did yesterday and saw the c0000005 error too, multiple times. I thought it might be something else than NAudio but it seems that it is the cause..

New Post: Access Violation Exception - 0xc0000005

$
0
0
My errors also happends randomly btw but i've only seen it on one of my PCs, running Windows 8.1. Never on my Windows 7.

New Post: Access Violation Exception - 0xc0000005

$
0
0
I'm afraid these types of thing can be very hard to track down. Make sure your drivers are up to date. Also consider using WaveOutEvent instead of DirectSoundOut to see if that improves matters.

New Post: NAudio doesn't record the microphone input without opening windows recorddevices

$
0
0
Hello,

I try to get the MasterPeakValue from the AudioMeterInformation, but everything I get is the value 0.

I only get some Input, if I open the windows mixer with the recording devices in it.

The devices are being enumerated via MMDeviceEnumeration. The device itself is in a variable (it's not null) from the type 'MMDevice'.

Is this Issue known by someone?

New Post: Access Violation Exception - 0xc0000005

$
0
0
Yup, thats a headache..

Which drivers are you reffering to, audio drivers, motherboard drivers or?

New Post: Access Violation Exception - 0xc0000005

$
0
0
Soundcard drivers, although motherboard ones might help too, if you are using onboard soundcards like Realtek, which have had issues with NAudio in the past. Personally, I don't use DirectSoundOut at all, so I don't really have a feel for its long-term stability. From the stack-trace, the Access Violation is happening in the call to Stop, so possibly something has already gone wrong that causes playback to unexpectedly stop at this point. Things like the computer hibernating / sleeping, or usb soundcards being unplugged could possibly cause this type of crash.

Created Unassigned: Exception when initializing device under WASAPI Exclusive mode [16463]

$
0
0
I'm trying to initialize a device in WASAPI exclusive mode and am seeing this exception:

> System.Runtime.InteropServices.COMException (0x88890019): Exception from HRESULT: 0x88890019
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at NAudio.CoreAudioApi.AudioClient.Initialize(AudioClientShareMode shareMode, AudioClientStreamFlags streamFlags, Int64 bufferDuration, Int64 periodicity, WaveFormat waveFormat, Guid audioSessionGuid) in C:\src\naudio-trunk\NAudio\CoreAudioApi\AudioClient.cs:line 63
at NAudio.Wave.WasapiOut.Init(IWaveProvider waveProvider) in C:\src\naudio-trunk\NAudio\Wave\WaveOutputs\WasapiOut.cs:line 370
at NAudio.Wave.WaveExtensionMethods.Init(IWavePlayer wavePlayer, ISampleProvider sampleProvider, Boolean convertTo16Bit) in C:\src\naudio-trunk\NAudio\Wave\WaveExtensionMethods.cs:line 35

After some digging I found out the likely culprit is buffer alignment - the error code is AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED and MSDN states that "The caller must call Initialize again with the aligned buffer size." (http://msdn.microsoft.com/en-us/library/windows/desktop/dd370875(v=vs.85).aspx)

In AudioClient.cs (NAudio trunk) I see that the Initialize() method is only called once, meaning if it fails, it's not called again with an aligned buffer size. I'm not sure how to approach it but found this interesting source: http://blogs.msdn.com/b/matthew_van_eerde/archive/2009/04/03/sample-wasapi-exclusive-mode-event-driven-playback-app-including-the-hd-audio-alignment-dance.aspx

New Post: Access Violation Exception - 0xc0000005

$
0
0
I'm using WaveOutEvent and get this error.

New Post: System.FormatException occured in NAudio.dll

$
0
0
So I've been working on a soundboard application for the past week, and I've pretty much gotten everything else in the application to work, except for that one error that I haven't been able to fix.

The error only occurs at runtime, and it doesn't crash the application, plus the audio file doesn't play, and I receive the error in console.

This is the part that attempts to play the file. I declared most if not all of the Naudio related things on the class level because I used them in other procedures.
 Private waveOut As New NAudio.Wave.WaveOut
 Dim intOutputDevices = waveOut.DeviceCount
 Dim deviceInfo As NAudio.Wave.WaveOutCapabilities

Private Sub playAudio(ByVal strFilePath As String, ByVal intDeviceNumber As Integer)

        Dim waveReader As New NAudio.Wave.WaveFileReader(strFilePath)
        waveOut.DeviceNumber = intDeviceNumber
        waveOut.Init(New NAudio.Wave.WaveChannel32(waveReader))
        waveOut.Play()

End Sub

Private Sub stopPlaying()
     waveOut.Stop()
End Sub
This is where I called the method. I stored the file names in a dictionary with the keys of the dictionary being the literal key that I press on my keyboard to play the audio file, and the value being the file name. GetAsyncKeyState is the function that checks for keypresses.
 For Each pair In KeyBindings

            If (GetAsyncKeyState(pair.Key)) Then

                For intOutputDevice = 0 To intOutputDevices - 1

                    deviceInfo = NAudio.Wave.WaveOut.GetCapabilities(intOutputDevice)

                    Try

                        If deviceInfo.ProductName.Contains(cboOutputDevice.SelectedItem) Then
                            playAudio(pair.Value, intOutputDevice)
                        End If

                    Catch ex As Exception

                        If cboOutputDevice.SelectedIndex = -1 Then
                            MsgBox("Please select an output device")
                            Return
                        End If

                        If Not IO.File.Exists(pair.Value) Then
                            MsgBox("File does not exist.")
                            Return
                        End If

                    End Try

                Next

            End If

        Next
Any help at all would be very much appreciated,

Thank you.

New Post: SampleProvider to Trigger Bluetooth Speaker

New Post: Playback Audio with FadeIn and FadeOut

$
0
0
Hello,

I want to build an Application which allows me to Playback some Audiofiles (.wav and .mp3), this was realy easy with an online Tutorial on Youtube [1].

My Problem is that i want to have an FadeIn when i press "Play" and an FadeOut when i press Stop. I found an solution[2] for naudio to do this but i cant bring this solution together with my existing code for normal Playback without Fading.

My Code:
OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Audio File (*.mp3;*.wav)|*.mp3;*.wav;";
            if (dialog.ShowDialog() != DialogResult.OK) return;
          
            if (this.audioFile.EndsWith(".mp3"))
            {
                NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(this.audioFile));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            }
            else if (this.audioFile.EndsWith(".wav"))
            {
                NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(this.audioFile));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            }
            else throw new InvalidOperationException("Not a correct audio file type.");          
            output = new NAudio.Wave.DirectSoundOut();         
            output.Init(stream);
            this.btn_play.Enabled = true;
My "Play" button Click-Event triggers only the output.play() function.

The Code i found online for Fading:
public class FadeInOutSampleProvider : ISampleProvider
{
    enum FadeState
    {
        Silence,
        FadingIn,
        FullVolume,
        FadingOut,
    }

    private readonly object lockObject = new object();
    private readonly ISampleProvider source;
    private int fadeSamplePosition;
    private int fadeSampleCount;
    private FadeState fadeState;

    public FadeInOutSampleProvider(ISampleProvider source)
    {
        this.source = source;
        this.fadeState = FadeState.FullVolume;
    }

    public void BeginFadeIn(double fadeDurationInMilliseconds)
    {
        lock (lockObject)
        { 
            fadeSamplePosition = 0;
            fadeSampleCount = (int)((fadeDurationInMilliseconds * source.WaveFormat.SampleRate) / 1000);
            fadeState = FadeState.FadingIn;
        }
    }

    public void BeginFadeOut(double fadeDurationInMilliseconds)
    {
        lock (lockObject)
        {
            fadeSamplePosition = 0;
            fadeSampleCount = (int)((fadeDurationInMilliseconds * source.WaveFormat.SampleRate) / 1000);
            fadeState = FadeState.FadingOut;
        }
    }

    public int Read(float[] buffer, int offset, int count)
    {
        int sourceSamplesRead = source.Read(buffer, offset, count);
        lock (lockObject)
        {
            if (fadeState == FadeState.FadingIn)
            {
                FadeIn(buffer, offset, sourceSamplesRead);
            }
            else if (fadeState == FadeState.FadingOut)
            {
                FadeOut(buffer, offset, sourceSamplesRead);
            }
            else if (fadeState == FadeState.Silence)
            {
                ClearBuffer(buffer, offset, count);
            }
        }
        return sourceSamplesRead;
    }

    private static void ClearBuffer(float[] buffer, int offset, int count)
    {
        for (int n = 0; n < count; n++)
        {
            buffer[n + offset] = 0;
        }
    }

    private void FadeOut(float[] buffer, int offset, int sourceSamplesRead)
    {
        int sample = 0;
        while (sample < sourceSamplesRead)
        {
            float multiplier = 1.0f - (fadeSamplePosition / (float)fadeSampleCount);
            for (int ch = 0; ch < source.WaveFormat.Channels; ch++)
            {
                buffer[offset + sample++] *= multiplier;
            }
            fadeSamplePosition++;
            if (fadeSamplePosition > fadeSampleCount)
            {
                fadeState = FadeState.Silence;
                // clear out the end
                ClearBuffer(buffer, sample + offset, sourceSamplesRead - sample);
                break;
            }
        }
    }

    private void FadeIn(float[] buffer, int offset, int sourceSamplesRead)
    {
        int sample = 0;
        while (sample < sourceSamplesRead)
        {
            float multiplier = (fadeSamplePosition / (float)fadeSampleCount);
            for (int ch = 0; ch < source.WaveFormat.Channels; ch++)
            {
                buffer[offset + sample++] *= multiplier;
            }
            fadeSamplePosition++;
            if (fadeSamplePosition > fadeSampleCount)
            {
                fadeState = FadeState.FullVolume;
                // no need to multiply any more
                break;
            }
        }
    }

    public WaveFormat WaveFormat
    {
        get { return source.WaveFormat; }
    }
}
my problem is to connect this sampleProvider to my Playback. Can somebody show a small example on how i do this.

Thanks in advance and sorry for my bad english.


Links:
[1] https://www.youtube.com/watch?v=2ij2vqgprU0
[2] http://stackoverflow.com/a/9471208

New Post: SampleProvider to Trigger Bluetooth Speaker

$
0
0
Cool it works bug was on my side ! I also test with white noise using SignalGenerator

New Post: Using BinaryReader with Wavestream problem

$
0
0
Good day everyone.

First of all a big thank you to Mark for doing such a great job on NAudio. The source code is very well written.

I seem to have hit a snag trying to get this to work. So here is the deal: I am reading an MP3 file with MP3FileReader... then converting with WaveStream... then using a binaryreader read a portion of the Wavestream converting the bytes to floats.

Here is the portion of the code that presumably does this:
 static void Main(string[] args)
        {
           
            WaveFormat wFormat = new WaveFormat(11025,16,1);

            int bSize = 11025*2*10;
            //short[] buffer = new short[bSize];
            float[] fBuff = new float[bSize*3];

            string file = args[0];

            using(Mp3FileReader mp = new Mp3FileReader(file))
            {
                using(WaveStream ws = new WaveFormatConversionStream(wFormat,mp))
                {
                    

                    using(BinaryReader bs = new BinaryReader(ws))
                    {
                        
                        int count = 0;
                        int pos = bSize*3; //skip 10 seconds
                        int length = (int)bs.BaseStream.Length;
                        int required = bSize * 3; // get 30 seconds
                     
                        bs.BaseStream.Seek(pos, SeekOrigin.Begin);
                       

                        while (pos < length && count < required)
                        {
                            fBuff[count] = (float)bs.ReadInt16();
                                // 5.
                            // Increment the variables.
                            pos++;
                            count++;
                        }
                        
                     }
                   

                 }
The code works fine but regardless of where I set "pos" the first approx 600 bytes (300 16 bit floats)are always 0.

Anyone have any idea why this is occurring and how to correct it.

Thanks in advance

Ray

New Post: NAudio source code modifications

$
0
0
@cuffindall: Thanks for sharing your mods.

@markheath: Yes. For the MediaFoundationTransform constructor change, I've done the following so that the application can control the buffer size

in NAudio\MediaFoundation\MediaFoundationTransform.cs
    /// <summary>
    /// Constructs a new MediaFoundationTransform wrapper
    /// </summary>
    /// <param name="sourceProvider">The source provider for input data to the transform</param>
    /// <param name="outputFormat">The desired output format</param>
    /// <param name="bufferLenMs">Source buffer size in Miliseconds</param>
    public MediaFoundationTransform(IWaveProvider sourceProvider, WaveFormat outputFormat, int bufferLenMs = 10)
    {
        this.outputWaveFormat = outputFormat;
        this.sourceProvider = sourceProvider;

        int bufferDiviser = 1000 / bufferLenMs;
        sourceBuffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond / bufferDiviser];
        outputBuffer = new byte[(outputWaveFormat.AverageBytesPerSecond / bufferDiviser) + outputWaveFormat.BlockAlign];
    }
And applied the new parameter to the constructors for MediaFoundationResampler in NAudio\Wave\WaveProviders\MediaFoundationResampler.cs as well

New Post: NAudio c2c FFT is very slow & Sync Wavestreams

$
0
0
Hello Mark,

I encountered the problem that your FFT class seems to be quite slow, taking about ~200ms for each 4096 sample aggregation. I optimized my code for drawing and measured it: taking about 15ms with the Marshal and Lockbits method. I also recognized, that other FFT sizes, e.g. 1024 are significantly faster. So, do you look forward to optimize your FFT class one day? Or can you tell me a lightning fast .NET alternative for complex to complex FFT computation?

The second problem I struggle at, is to play Wavestreams on multiple devices at the same time and encounter delays that are clearly hearable. Especially when the Wavestream needs to decompress the samples. So, how can you synchronize several Wavestreams without too much delay und without interruptions in playback?

Kind regards

Freefall




About Flac Decoder news:



PS: Thefiloe in the end changed his mind, he said that his flac decoder may not be used in NAudio for an unknown reason. I can´t follow this small minded behaviour, I´m sorry for him.
He has already given permission and the plugin is finished now. So I let it published on google code. Anyway legit, as CSCore is MS-PL.

New Post: How about adding *.flac support?

$
0
0
Flac Decoder news:


PS: Thefiloe in the end changed his mind, he said that his flac decoder may not be used in NAudio for an unknown reason. I can´t follow this small minded behaviour. I´m sorry for him and I´m a bit angry. He has been already given the permission and the plugin is finished now. So I let it published on google code, for those who need it anyway.

http://code.google.com/p/naudio-flac/source/browse/#svn%2Ftrunk%2Fbin%2FDebug

It´s damn legit anyway, as CSCore is MS-PL. Credited him of course for his work though.


Freefall
Viewing all 5831 articles
Browse latest View live


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