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

New Post: Play mp3 from stream in real-time

$
0
0

I solved the problem. Just drop frames, which were randomly properties, and add those frames whose properties match more than 10 times.Maybe i someone  help with the error "AcmNotPossible calling acmStreamConvert".Sorry for bad english and bad code =)

privatevoid StreamMP3(object state)
        {
            fullyDownloaded = false;var url = (string) state;
            webRequest = (HttpWebRequest) WebRequest.Create(url);
            HttpWebResponse resp = null;try
            {
                resp = (HttpWebResponse) webRequest.GetResponse();
            }catch (WebException e)
            {if (e.Status != WebExceptionStatus.RequestCanceled)
                {
                    ShowError(e.Message);
                }return;
            }var buffer = newbyte[16384*4]; // needs to be big enough to hold a decompressed frameconstint maxMatchedFrames = 10;int matchedFramesCount = 0;int sampleRate = 44100;var channelMode = ChannelMode.JointStereo;var queueMatchedFrames = new Queue<Mp3Frame>();bool matchedFramesReady = false;
            IMp3FrameDecompressor decompressor = null;try
            {using (Stream responseStream = resp.GetResponseStream())
                {var readFullyStream = new ReadFullyStream(responseStream);do
                    {if (bufferedWaveProvider != null&&
                            bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes <
                            bufferedWaveProvider.WaveFormat.AverageBytesPerSecond/4)
                        {
                            Debug.WriteLine("Buffer getting full, taking a break");
                            Thread.Sleep(100);
                        }else
                        {
                            Mp3Frame frame = null;try
                            {
                                frame = Mp3Frame.LoadFromStream(readFullyStream);if (frame == null) break;if (!matchedFramesReady)
                                {if ((frame.SampleRate == sampleRate) && (frame.ChannelMode == channelMode))
                                    {
                                        queueMatchedFrames.Enqueue(frame);
                                        matchedFramesCount++;if (matchedFramesCount == maxMatchedFrames)
                                        {
                                            matchedFramesReady = true;
                                        }
                                    }else
                                    {
                                        queueMatchedFrames.Clear();
                                        sampleRate = frame.SampleRate;
                                        channelMode = frame.ChannelMode;
                                        matchedFramesCount = 0;
                                    }
                                }
                            }catch (EndOfStreamException)
                            {
                                fullyDownloaded = true;break;
                            }catch (WebException)
                            {break;
                            }if (!matchedFramesReady) continue;if (decompressor == null)
                            {
                                WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate,
                                                                          frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                                                                          frame.FrameLength, frame.BitRate);
                                decompressor = new AcmMp3FrameDecompressor(waveFormat);
                                bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
                                bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(10);
                            }int decompressed = decompressor.DecompressFrame(queueMatchedFrames.Count != 0
                                                                                ? queueMatchedFrames.Dequeue()
                                                                                : frame, buffer, 0);
                            bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
                        }
                    } while (playbackState != StreamingPlaybackState.Stopped);
                }
            }finally
            {if (decompressor != null)
                {
                    decompressor.Dispose();
                }
                queueMatchedFrames.Clear();
            }
        }


Commented Issue: Whole MF Encoder does not work [16382]

$
0
0
If I encode any file to any format using your encoder in the wpf sample on win8x64 prof. it fails. If I play the file there is just a strange noise. And on some targetformats there is an Exceptoin in MediaFoundationEncoder::PerformEncoder in line writer.BeginWriting();
Comments: I've done a few quick tests running as an x64 process (the WPF demo runs by default as x86) and encoding is working fine for me. I do need more information if you want me to attempt to fix your problem. Otherwise I'll close the issue.

Source code checked in, #52dd2b311b24

$
0
0
minor updates ready for another alpha nuget release

Source code checked in, #9870f299a6de

Created Issue: WasapiLoopbackCapture doesn't capture silence [16383]

$
0
0
Description:
When recording using WasapiLoopbackCapture, if all audio inputs go silent then the data available callback always returns 0 bytes recorded. This means that if you are recording to a file and you play one sound, it will record it, but then if you allow 10 seconds of silence in between and then play another sound, in the audio file the two sounds will appear right next to each other (without the 10 second silence).

Expected:
Silence should be included as data, even if it's empty data.

Repro:
1. Create a WasapiLoopbackCapture.
2. Register a DataAvailable callback and print out bytes received in callback
3. Call StartRecording
4. Turn off all audio
Note: Does not always occur, sometimes silence is recorded.

Other:
The silence case was also mentioned here: http://naudio.codeplex.com/discussions/203605
I looked into the code, it seems to be occurring in 'ReadNextPacket' where capture.GetNextPacketSize(); always returns 0 during silence, instead of returning a non-zero value and setting the silence flag. Not sure how to fix this :/

Commented Issue: WasapiLoopbackCapture doesn't capture silence [16383]

$
0
0
Description:
When recording using WasapiLoopbackCapture, if all audio inputs go silent then the data available callback always returns 0 bytes recorded. This means that if you are recording to a file and you play one sound, it will record it, but then if you allow 10 seconds of silence in between and then play another sound, in the audio file the two sounds will appear right next to each other (without the 10 second silence).

Expected:
Silence should be included as data, even if it's empty data.

Repro:
1. Create a WasapiLoopbackCapture.
2. Register a DataAvailable callback and print out bytes received in callback
3. Call StartRecording
4. Turn off all audio
Note: Does not always occur, sometimes silence is recorded.

Other:
The silence case was also mentioned here: http://naudio.codeplex.com/discussions/203605
I looked into the code, it seems to be occurring in 'ReadNextPacket' where capture.GetNextPacketSize(); always returns 0 during silence, instead of returning a non-zero value and setting the silence flag. Not sure how to fix this :/
Comments: yes, unfortunately this is how WASAPI loopback capture works. You could fool windows by playing a stream of silence throughout the duration of the capture. Alternatively, you'd need to timestamp captured audio and insert the silence yourself. It's very annoying but not really a bug in NAudio.

Commented Issue: Conversion to Float is wrong [16380]

$
0
0
This code is from SimpleCompressorStream there is the followig code
left = BitConverter.ToInt16(buffer, start) / 32768.0;

that is wrong because max short is 32767 while min short is -32768

the resulting code will span ranges from[-1 to 0.99999999999999999]
Comments: If you are interested in an explanation of why the range of values for floating point is -1 to 0.9999 then there is one in Will Pirkle's book "Designing Audio Effect Plug-Ins in C++"

Closed Issue: Conversion to Float is wrong [16380]

$
0
0
This code is from SimpleCompressorStream there is the followig code
left = BitConverter.ToInt16(buffer, start) / 32768.0;

that is wrong because max short is 32767 while min short is -32768

the resulting code will span ranges from[-1 to 0.99999999999999999]
Comments: no plan to change this behaviour

Commented Issue: WasapiLoopbackCapture doesn't capture silence [16383]

$
0
0
Description:
When recording using WasapiLoopbackCapture, if all audio inputs go silent then the data available callback always returns 0 bytes recorded. This means that if you are recording to a file and you play one sound, it will record it, but then if you allow 10 seconds of silence in between and then play another sound, in the audio file the two sounds will appear right next to each other (without the 10 second silence).

Expected:
Silence should be included as data, even if it's empty data.

Repro:
1. Create a WasapiLoopbackCapture.
2. Register a DataAvailable callback and print out bytes received in callback
3. Call StartRecording
4. Turn off all audio
Note: Does not always occur, sometimes silence is recorded.

Other:
The silence case was also mentioned here: http://naudio.codeplex.com/discussions/203605
I looked into the code, it seems to be occurring in 'ReadNextPacket' where capture.GetNextPacketSize(); always returns 0 during silence, instead of returning a non-zero value and setting the silence flag. Not sure how to fix this :/
Comments: Ahh didn't know this was a feature :P Thanks Mark! Feel free to close this bug then. I'll attempt the route of playing silence to the device, though I have had a not easily reproducible crash that occurred when playing audio to the same device that the loopback capture was using.

Commented Issue: WasapiLoopbackCapture doesn't capture silence [16383]

$
0
0
Description:
When recording using WasapiLoopbackCapture, if all audio inputs go silent then the data available callback always returns 0 bytes recorded. This means that if you are recording to a file and you play one sound, it will record it, but then if you allow 10 seconds of silence in between and then play another sound, in the audio file the two sounds will appear right next to each other (without the 10 second silence).

Expected:
Silence should be included as data, even if it's empty data.

Repro:
1. Create a WasapiLoopbackCapture.
2. Register a DataAvailable callback and print out bytes received in callback
3. Call StartRecording
4. Turn off all audio
Note: Does not always occur, sometimes silence is recorded.

Other:
The silence case was also mentioned here: http://naudio.codeplex.com/discussions/203605
I looked into the code, it seems to be occurring in 'ReadNextPacket' where capture.GetNextPacketSize(); always returns 0 during silence, instead of returning a non-zero value and setting the silence flag. Not sure how to fix this :/
Comments: Making a WaveOut that plays silence works well thus far! Maybe that could be a feature of the WasapiLoopbackCapture?

New Post: Getting error while mixing more audios like above 5 numbered.

$
0
0

Hi All,

I am using naudio for mixing the audio files.Its a great tool .But unfortunately i am getting errors while i am mixing the more than 5 to 6 files( but they are less in size like just below 1min in length).

Some times 4th one coming at position 6 in the final out put so please once review this and let me know is there any possibilities to come out from this problem..

cod ei am using is  ::

 MemoryStream memStream = new MemoryStream();

        WaveStream originalStream = new WaveFileReader(fileName);
        var pcmStream = WaveFormatConversionStream.CreatePcmStream(originalStream);
        var blockAlignReductionStream = new BlockAlignReductionStream(pcmStream);
        var waveFormatConversionStream = new WaveFormatConversionStream(
            new WaveFormat(44100, blockAlignReductionStream.WaveFormat.BitsPerSample, 2), blockAlignReductionStream);
        //var waveOffsetStream = new WaveOffsetStream(waveFormatConversionStream);
        var audioOffsetted = new WaveOffsetStream(
 pcmStream, TimeSpan.FromSeconds(offset), TimeSpan.Zero, pcmStream.TotalTime);
        WaveChannel32 wavch = new WaveChannel32(audioOffsetted);
        return wavch;

New Post: Change Buffer WasapiLoopbackCapture

$
0
0

First of all thank you for this great piece of work - it is so easy to use...

My problem is, when I am recording audio via WasapiLoopbackCapture and start another process with a bit heavier cpu-load, I get a faulty recording with skips. When the system is nearly "idle" everything works great. Do I have to change the buffer size? When yes, how can I do this?

Thanks in advance!

New Post: WaveIn differs in FormApplication and Console Application

$
0
0

I can use

WaveIn wi = new WaveIn() in a form application,

but if it is a console application it gives an exception that is

"Use WaveInEvent to record on a background thread"

What can be the problem?

New Post: WaveIn differs in FormApplication and Console Application

$
0
0

I have changed waveIn class with WaveInEvent class, and the problem is solved now.  have only changed the variable decleration, is there anything that must be handled?

New Post: volumeSlider isn't drawing to my form for some reason.

$
0
0

This is my code to draw it (ripped almost entirely from the demo app):

 

this.volumeSlider.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.volumeSlider.Location = new System.Drawing.Point(358, 267);
            this.volumeSlider.Name = "volumeSlider1";
            this.volumeSlider.Size = new System.Drawing.Size(96, 16);
            this.volumeSlider.TabIndex = 11;

 

 

It's not throwing any errors at me, it just isn't drawing, regardless of where on the form I place it. Any suggestions?


Updated Wiki: Convert a MP3 to WAV

$
0
0

MP3

Convert an MP3 to WAV

1) Add the using references for NAudio to your project:

using NAudio;
using NAudio.Wave;

2) Assuming that you are going to find the location of a MP3 and save the WAV file to the same location:

public static void Mp3ToWav(string mp3File, string outputFile)
{
    using (Mp3FileReader reader = new Mp3FileReader(mp3File))
    {
        WaveFileWriter.CreateWaveFile(outputFile, reader);
    }
}

3) You now have a WAV file in the directory of your MP3.

 

The complete sample program:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using NAudio;
using NAudio.Wave;

namespace ConvertMP3toWAV
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void cmbOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "MP3 Files (*.mp3)|*.mp3|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtLocation.Text = openFileDialog.FileName;
            }
        }

        private void cmbConvert_Click(object sender, EventArgs e)
        {
            string outputFileName = txtLocation.Text;
            outputFileName = outputFileName.Substring(0, txtLocation.TextLength - 3) + "wav";
            Mp3ToWav(txtLocation.Text, outputFileName);
        }

        public static void Mp3ToWav(string mp3File, string outputFile)
        {
            using (Mp3FileReader reader = new Mp3FileReader(mp3File))
            {
                WaveFileWriter.CreateWaveFile(outputFile, reader);
            }
        }
    }
}

Updated Wiki: Documentation

$
0
0

The NAudio Documentation Wiki

NAudio FAQ

What is NAudio?

NAudio is an open source audio API for .NET written in C# by Mark Heath, with contributions from many other developers. It is intended to provide a comprehensive set of useful utility classes from which you can construct your own audio application.

Why NAudio?

NAudio was created because the Framework Class Library that shipped with .NET 1.0 had no support for playing audio. The System.Media namespace introduced in .NET 2.0 provided a small amount of support, and the MediaElement in WPF and Silverlight took that a bit further. The vision behind NAudio is to provide a comprehensive set of audio related classes allowing easy development of utilities that play or record audio, or manipulate audio files in some way.

Can I Use NAudio in my Project?

NAudio is licensed under the Microsoft Public License (Ms-PL) which means that you can use it in whatever project you like including commercial projects. Of course we would love it if you share any bug-fixes or enhancements you made to the original NAudio project files.

Is .NET Performance Good Enough for Audio?

While .NET cannot compete with unmanaged languages for very low latency audio work, it still performs better than many people would expect. On a fairly modest PC, you can quite easily mix multiple WAV files together, including pass them through various effects and codecs, play back glitch free with a latency of around 50ms.

How can I get help?

There are three main ways to get help. If you have a specific question concerning how to use NAudio, then I recommend that you ask onStackOverflow and tag your question with naudio. This gives you the best chance of getting a quick answer. You can also ask a question on theNAudio discussion forums here on CodePlex. I attempt to answer all questions, but since this is a spare time project, occasionally I get behind. Finally, I am occasionally able to offer paid support for situations where you need quick advice, bugfixes or new features. Use the contact feature of the Codeplex website to get in touch withMark Heath if you wish to pursue this option.

How do I submit a patch?

I welcome contributions to NAudio and have accepted many patches, but if you want your code to be included, please familiarise yourself with the following guidelines:

  • Your submission must be your own work, and able to be released under the MS-PL license.
  • You will need to make sure your code conforms to the layout and naming conventions used elsewhere in NAudio.
  • Remember that there are many existing users of NAudio. A patch that changes the public interface is not likely to be accepted.
  • Try to write "clean code" - avoid long functions and long classes. Try to add a new feature by creating a new class rather than putting loads of extra code inside an existing one.
  • I don't usually accept contributions I can't test, so please write unit tests (using NUnit) if at all possible. If not, give a clear explanation of how your feature can be unit tested and provide test data if appropriate. Tell me what you did to test it yourself, including what operating systems and soundcards you used.
  • If you are adding a new feature, please consider writing a short tutorial on how to use it.
  • Unless your patch is a small bugfix, I will code review it and give you feedback. You will need to be willing to make the recommended changes before it can be integrated into the main code.
  • The easiest way to provide a patch is to create your own fork on Mercurial and issue a pull request. Seethis video if you are new to Mercurial.
  • Please also bear in mind that when you add a feature to NAudio, that feature will generate future support requests and bug reports. Are you willing to stick around on the forums and help out people using it?

How do I...?

The best way to learn how to use NAudio is to download the source code and look at the two demo applications - NAudioDemo and NAudioWpfDemo. These demonstrate several of the key capabilities of the NAudio framework. They also have the advantage of being kept up to date, whilst some of the tutorials you will find on the internet refer to old versions of NAudio.

Getting Started with NAudio – Downloading and Compiling

  1. Download a copy of the NAudio source code (or a pre-compiled version but the newest available code is available in source form first).
    http://naudio.codeplex.com/SourceControl/list/changesets
  2. The default project is set to the NAudio class library. Class Library’s don’t have anything to look at when you press F5. If this is your first time with NAudio, set the start-up project asNAudioDemo and then hit F5. The NAudioDemo project shows the base functionality you can utilise through your own project.
  3. In the BIN directory for the built solution, you can find a copy of the NAudio library for using and referencing in your own project. Make sure that you grab a copy of the NAudio.XML file as well if your copying it over to your own projects directory, that way you will have the intellisense documentation for use in Visual Studio when working with the NAudio API.

Additional Tutorials from OpenSebJ's blog (n.b. these are for NAudio 1.3):

http://stackoverflow.com/

New Post: Can I Use NAudio library for commercial purpose?

$
0
0

Hi All,

Can I Use NAudio library for commercial purpose?

Regards

Anudeep

New Post: How can I clip the region of a audio file and save it as different audio?

$
0
0

Hi all,

How can I clip the region of a audio file and save it as different audio?

 

Regards

Anudeep

New Post: MP3 Stream From Hard Drive

$
0
0

the MP3 reader does look through the file allowing it to create a "table of contents" so it can support fast and accurate repositioning. You could take a copy of the MP3 file reader code and just remove the TOC generation if you wanted. There is also a demo of streaming MP3 over the internet in NAudioDemo, which obviously by its nature, doesn't read ahead. You simply parse MP3 frames and decompress them.

Mark

Viewing all 5831 articles
Browse latest View live


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