How to get current time while streaming mp3 using NAudio? - c#

I have a code to stream mp3 from url. I want to show the current time of the mp3 player in UI. I tried it using WaveOut.GetPosition, but it couldn't work for me.
How can I do that?
My code:
do
{
//..codes to get url stream,to create BufferedWaveProvider
int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
provider.AddSamples(buffer, 0, decompressed);
if (provider.BufferedDuration.Seconds > 2 && waveOut == null)
{
waveOut = new WaveOut();
waveOut.Init(provider);
waveOut.Play();
}
if (waveOut != null)
{
currentTime = (int)(waveOut.GetPosition() * 1d / AvgBytesPerSec);
}
}
while (bytesRead > 0 || waveOut.PlaybackState == PlaybackState.Playing);

I think the only change you need to make to your code is to use waveOut.OutputWaveFormat.AverageBytesPerSecond instead of the AvgBytesPerSec property you are currently using. The IWavePosition interface (which is what you are actually using here) "thinks" in hardware terms, so if you are using a format that has to be converted before the hardware can use it, the hardware byte rate will be different than your source byte rate.
Note that the position returned by GetPosition() is only since playback was last started. If waveOut.Stop() is called, the position is reset to 0 when playback is started again. Mapping the position to the source is up to the caller (which is really simple; just track where you last started playback on the source and add it to the position returned. Buffering makes it more complicated, but still completely doable).
I wrote the original IWavePosition interface & implementations for NAudio. It works great in the project I built it for. :)

did you try the property current time and property position?
mp3Reader = new Mp3FileReader("example.mp3");
waveOut.Init(mp3Reader);
waveOut.Play();
// reposition to five seconds in
mp3Reader.CurrentTime = TimeSpan.FromSeconds(5.0);
so mp3Reader.CurrentTime should give you what you need I think
Hope this will help you

Related

Get Basic audio spectrum data in unity

I want to visualize if an audio clip has sound or not. The microphone and the
audiosource is working correctly but I am stuck with its visualizing part. I have hard time understanding the official document and I want a solution.
I tried the following code:
void Update () {
AnalyzeSound();
text1.text = "sound!\n"+ " rmsValue : " + rmsValue ;
}
void AnalyzeSound()
{
audio.GetOutputData(samples, 0);
//GetComponent rms
int i = 0;
float sum = 0;
for (; i < SAMPLE_SIZE; i++)
{
sum = samples[i] * samples[i];
}
rmsValue = Mathf.Sqrt(sum / SAMPLE_SIZE);
//get the dbValue
dbValue = 20 * Mathf.Log10(rmsValue / 0.1f);
}
Can I take rmsValue as the input of sound on microphone? or should I take the dbValue? what should be the threshold value?
in a few words, When can I say the microphone has sound?
There is no hard and fast definition that would separate noise from silence in all cases. It really depends on how loud the background noise is. Compare for example, silence recorded in an anechoic chamber vs silence recorded next to an HVAC system. The easiest thing to try is to experiment with different dB threshold values below which you consider the signal as noise and above which it is considered signal. Then adjust the threshold value up or down to suit your needs. Depending on the nature of the signal (e.g. music vs. speech) you could look into other techniques such as Voice Activity Detection (https://en.wikipedia.org/wiki/Voice_activity_detection) or a convolutional neural network to segment speech and music

reduce CPU overhead while proccessing Video Stream

I am developing C# WPF Auto Number Plate Recognition Using an OCR.
The Flow is, i am getting a pictures from a video stream MJPEG and this images should be passed to the OCR to get the plate number and other details.
The problem is : the Video stream is producing about 30 Frame/second and the CPU can't handle this much of processing also it will take around 1 Sec to process 1 frame, Also when i will get many frames on the Queue the CPU will be 70% used (Intel I7 4th G).
Can anyone suggest solution and better implementation.
//This is the queue where it will hold the frames
// produced from the video streaming(video_Newfram1)
private readonly Queue<byte[]> _anpr1Produces = new Queue<byte[]>();
//I am using AForg.Video to read the MJPEG Streaming
//this event will be triggered for every frame
private void video_NewFrame1(object sender, NewFrameEventArgs eventArgs)
{
var frameDataAnpr = new Bitmap(eventArgs.Frame);
AnprCam1.Source = GetBitmapimage(frameDataAnpr);
//add current fram to the queue
_anpr1Produces.Enqueue(imgByteAnpr);
//this worker is the consumer that will
//take the frames from the queue to the OCR processing
if (!_workerAnpr1.IsBusy)
{
_workerAnpr1.RunWorkerAsync(imgByteAnpr);
}
}
//This is the consumer, it will take the frames from the queue to the OCR
private void WorkerAnpr1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
if (_anpr1Produces.Count <= 0) continue;
BgWorker1(_anpr1Produces.Dequeue());
}
}
//This method will process the frames that sent from the consumer
private void BgWorker1(byte[] imageByteAnpr)
{
var anpr = new cmAnpr("default");
var objgxImage = new gxImage("default");
if (imageByteAnpr != null)
{
objgxImage.LoadFromMem(imageByteAnpr, 1);
if (anpr.FindFirst(objgxImage) && anpr.GetConfidence() >= Configs.ConfidanceLevel)
{
var vehicleNumber = anpr.GetText();
var vehicleType = anpr.GetType().ToString();
if (vehicleType == "0") return;
var imagename = string.Format("{0:yyyy_MMM_dd_HHmmssfff}", currentDateTime) + "-1-" +
vehicleNumber + ".png";
//this task will run async to do the rest of the process which is saving the vehicle image, getting vehicle color, storing to the database ... etc
var tsk = ProcessVehicle("1", vehicleType, vehicleNumber, imageByteAnpr, imagename, currentDateTime, anpr, _anpr1Produces);
}
else
{
GC.Collect();
}
}
}
What you should do is this:
First, figure out if a frame is worth processing or not. If you're using a compressed video stream, you can usually quickly read the frame's compressed size. It stores the difference between the current frame and the previous one.
When it's small, not much changed (i.e: no car drove by).
That's a low-tech way to do motion detection, without even having to decode a frame, and it should be extremely fast.
That way, you can probably decide to skip 80% of the frames in a couple of milliseconds.
Once and a while you'll get frames that need processing. Make sure that you can buffer enough frames so that you can keep recording while you're doing your slow processing.
The next thing to do is find a region of interest, and focus on those first. You could do that by simply looking at areas where the color changed, or try to find rectangular shapes.
Finally, one second of processing is SLOW if you need to process 30 fps. You need to make things faster, or you'll have to build up a gigantic buffer, and hope that you'll ever catch up if it's busy on the road.
Make sure to make proper use of multiple cores if they are available, but in the end, knowing which pieces of the image are NOT relevant is the key to faster performance here.

Using Naudio WaveIn for both performing FFT transformation and writing to disk in real-time (NOT ASIO)

I am currently creating a Winforms application for Windows 8.1, I have been able to perform an FFT on the input data from the devices microphone using ASIO Out, however to be able to use ASIO on my machine I needed to download ASIO4ALL,
This is causing a huge amount of feedback in the microphone and is resulting in very inaccurate frequency readings (to make sure it was the sound itself I wrote a copy to disc to playback),
So to get around this I have been trying to adapt my code to work with Naudio's WaveIn class, however this is returning either no data or NaN for the FFT algorithm (although I can save a recording to disk which plays back with no issues),
I've been trying to fix this for some time now and am sure it is just a silly mistake somewhere, any help would be greatly appreciated!
Below is the code for the "OnDataAvailable" event (where I'm 99% sure I am going wrong):
void OnDataAvailable(object sender, WaveInEventArgs e)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new EventHandler<WaveInEventArgs>(OnDataAvailable), sender, e);
}
else
{
byte[] buffer = e.Buffer;
int bytesRecorded = e.BytesRecorded;
int bufferIncrement = waveIn.WaveFormat.BlockAlign;
for (int index = 0; index < bytesRecorded; index += bufferIncrement)
{
float sample32 = BitConverter.ToSingle(buffer, index);
sampleAggregator.Add(sample32);
}
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
}
}
If any more details and/or code is required please let me know.
waveFile: Name of the file writer
e.Buffer: The buffer containing the recorded data
e.BytesRecorded: The total number of bytes recorded
For reference below is the working code when using the ASIO class:
void asio_DataAvailable(object sender, AsioAudioAvailableEventArgs e)
{
byte[] buf = new byte[e.SamplesPerBuffer * 4];
for (int i = 0; i < e.InputBuffers.Length; i++)
{
Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer * 4);
}
for (int i = 0; i < e.SamplesPerBuffer * 4; i++)
{
float sample32 = Convert.ToSingle(buf[i]);
sampleAggregator.Add(sample32);
}
}
EDIT: The samples which are being returned are now accurate after changing the convert statement to Int16 as per the advice on this page, I had some other issues in my code which prevented actual results from being returned originally.
However, the file which is being written to disk is very choppy, I'm sure this is a problem with my laptop and the number of processes which is trying to perform, could anyone please advise a way around this issue?
In the NAudio WPF demo project there is an example of calculating FFTs while playback is happening with a class called SampleAggregator, that stores up blocks of 1024 samples and then performs FFTs on them.
It looks like you are trying to do something similar to this. I suspect the problem is that you are getting 16 bit samples, not 32 bit. Try using BitConverter.ToShort on every pair of bytes.
mWaveInDevice = new WaveIn();
mWaveInDevice.WaveFormat = WaveFormat.**CreateIeeeFloatWaveFormat(44100,2)**;
Set CreateIeeeFloatWaveFormat for WaveFormat, and then you will get right values after fft.

playing array filled with pcm values in real time

I need to be able to play a short[] array filled with 16-bit PCM values (after decode) in real time.
The array keeps getting longer and the player should be able to play it while the array is "growing".
I an writing in C#.
thanks ahead,
Ofek
EDIT:
I used the BufferedWaveProvider and the code looks like this:
Class Player
{
Private WaveFormat waveForamt=new WaveFormat(8000,16,1);
private BufferedWaveProvider bufferedWaveProvider;
public Player()
{
bufferedWaveProvider=new BufferedWaveProvider(waveFormat);
}
public void AddSamples(byte[] array)
{
bufferedWaveProvider.AddSamples(array,0,array.length);
WaveOut waveout=new WaveOut();
waveout.Init(bufferedWaveProvider);
waveout.Play();
}
}
the array that the AddSamples func gets is 32000 long I can see the parameters
bufferedWaveProvider.BufferedBytes = 32000
bufferedWaveProvider.BufferedBytes = 80000
bufferedWaveProvider.BufferedDuration = 00:00:02
bufferedWaveProvider.BufferDuration = 00:00:05
when I record the array I speak for 2 seconds and say: "one, two, three..."
The porblem is that when I play it, I just hear a quick sound, and nothing like what I said..
any ideas about what went wrong?
Thnaks, Ofek
EDIT 2:
Now my code looks like this, I call the AddSamples function from the Capture class.
after each time the waveout.Play() function is called - I clear the buffer and wait for it to fill up again. once it is full again I play it, and so on. the problem is that in the second time I play the buffer the sound starts fast and then it slows down... I heard something about working with two buffers.. do you know anything about this?
Thnaks a lot!
Here is the class that calls the player.AddSamples
You basically need to be able to set up a soundcard driver to read from an audio buffer and then write to that same buffer. The BufferedWaveProvider class in naudio could help. Take a look at http://naudio.codeplex.com/.
Edit : Your class works fine for me in an empty 'forms' project, playing 2 seconds of audio:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var player = new Player();
var rand = new Random();
var bytes = new byte[32000];
rand.NextBytes(bytes);
player.AddSamples(bytes);
}
}
Are you calling it in a background thread, or maybe a console app? It May be a threading or callback issue - see the 1) WaveOut section in http://naudio.codeplex.com/wikipage?title=Audio%20Output%20Driver%20Selection. You may need to pass different callback options into WaveOut()?

Converting a WAV file to a spectrogram

Hi im very new to this thing so please bear with me. I am trying to convert a WAV file to a spectrogram but arent sure how to begin with. I read on something that says to read the PCM data(which i think is my WAV file) and store it in an array in the WavReader class before apply the FFT on it and converting it to GUI. Im currently using Naudio to achieve this but could not find anything that shows how to convert the WAV file to a spectrogram. Thanks
Edit :
I found out about converting PCM to FFT with Naudio and im stuck.
using (var reader = new AudioFileReader("test1.wav"))
{
// test1.wav is my file to process
// test0.wav is my temp file
IWaveProvider stream16 = new WaveFloatTo16Provider(reader);
using (WaveFileWriter converted = new WaveFileWriter("test0.wav", stream16.WaveFormat))
{
// buffer length needs to be a power of 2 for FFT to work nicely
// however, make the buffer too long and pitches aren't detected fast enough
// successful buffer sizes: 8192, 4096, 2048, 1024
// (some pitch detection algorithms need at least 2048)
byte[] buffer = new byte[8192];
int bytesRead;
do
{
bytesRead = stream16.Read(buffer, 0, buffer.Length);
converted.WriteData(buffer, 0, bytesRead);
} while (bytesRead != 0 && converted.Length < reader.Length);
}
}
Edit : I would also like to know if it is possible to compare 2 spectrograms of 2 different files programmatically.
You could also use BASS.NET library which natively provides all these features and is free.
The Visuals.CreateSpectrum3DVoicePrint Method does exactly that.
Feel free to ask for assistance if you're having a hard time using it.
EDIT : here's a quick and dirty sample
public partial class Form1 : Form
{
private int _handle;
private int _pos;
private BASSTimer _timer;
private Visuals _visuals;
public Form1()
{
InitializeComponent();
}
private void timer_Tick(object sender, EventArgs e)
{
bool spectrum3DVoicePrint = _visuals.CreateSpectrum3DVoicePrint(_handle, pictureBox1.CreateGraphics(),
pictureBox1.Bounds, Color.Cyan, Color.Green,
_pos, false, true);
_pos++;
if (_pos >= pictureBox1.Width)
{
_pos = 0;
}
}
private void Form1_Load(object sender, EventArgs e)
{
string file = "..\\..\\mysong.mp3";
if (Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, Handle))
{
_handle = Bass.BASS_StreamCreateFile(file, 0, 0, BASSFlag.BASS_DEFAULT);
if (Bass.BASS_ChannelPlay(_handle, false))
{
_visuals = new Visuals();
_timer = new BASSTimer((int) (1.0d/10*1000));
_timer.Tick += timer_Tick;
_timer.Start();
}
}
}
}
EDIT 2
You can provide a file name but you can also provide your own audio data using the other overload that accepts an IntPtr or use Bass.BASS_StreamCreatePush with Bass.BASS_StreamPutData.
Regarding comparing spectrograms you could do the following :
Resize the image to a smaller size, reduce information by dithering it to 8-bit (with a good algorithm however)
Compare the two images
However for comparing audio data I'd strongly suggest you to use fingerprints, it roughly does that but is much more robust than my suggestion.
Here's a fingerprinting library that is free to use :
http://www.codeproject.com/Articles/206507/Duplicates-detector-via-audio-fingerprinting
Not entirely sure it would work for small samples, though.
EDIT 3
I'm afraid I can't find the link where I've read that but that's what they do: reducing data and comparing images such as the example below (last image):
(note : not to compare at all with image 1, it's something else but just to show why using a lower resolution might give better yields)
(from http://blog.echonest.com/post/545323349/the-echo-nest-musical-fingerprint-enmfp)
Now a very basic explanation of the process:
Comparison source A:
Comparison source B: (I've just changed a region of A)
Comparison result:
(done with Paint.Net by adding the former images as layers and setting 2nd layer blending to difference instead of normal)
If the fingerprints were to be identical the resulting image would be completely black.
And by reducing data to a 8-bit image you are easing the comparison process but keep in mind you will need a good dithering algorithm.
This is one is quite good :
http://www.codeproject.com/Articles/66341/A-Simple-Yet-Quite-Powerful-Palette-Quantizer-in-C
Well it's not on par with Photoshop or Hypersnap's one (which IMO is exceptional) but that might be enough for the task.
And avoid at all costs Floyd–Steinberg dithering or something that does error diffusion.
Here some attempts on creating dithering algorithms : http://bisqwit.iki.fi/story/howto/dither/jy/
Take this with caution as I'm not an expert in the field but that's roughly how it's done.
Go to https://dsp.stackexchange.com/ and ask a few questions there, you might get useful hints on achieving this.

Categories