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

New Post: Determine which application is playing audio

$
0
0
Say I had a range of music applications (iTunes, Spotify, and Chrome). I want to determine if audio is playing and which application is playing audio. I can get and save music, playing through the speakers (wasapiloopback). I just don't know if it's possible to track down which application is doing it.

I'm writing in VB.NET.

New Post: How to play several audio with different volume

New Post: How to play several audio with different volume

$
0
0
Use WaveOut.Volume property for this

New Post: Determine which application is playing audio

$
0
0
Have a look at core audio api included in naudio

New Post: Speed and pitch (?)

New Post: How to play several audio with different volume

$
0
0
if you reduce the sound waveout ( 1 ) , and the decrease of the sound and waveout ( 2 )

New Post: How to play several audio with different volume

$
0
0
Freefall wrote:
Use WaveOut.Volume property for this
if you reduce the sound waveout ( 1 ) , and the decrease of the sound and waveout ( 2 )

New Post: How to change the speaker volume by c # Naudio?

$
0
0
How to change the speaker volume by c # Naudio?

New Post: How to play several audio with different volume

$
0
0
Dude, I don´t understand what your problem is. Despite the fact, you got all you need to know, why you spam the forum with one more thread?

I shouldn´t do this, as you learn nothing when I write the code for you...
'
'VB .NET Example Code
'
Private Sub RunSeveralPlaybacks()

    Dim WaveOut1 As New WaveOut()
    Dim WaveOut2 As New WaveOut()

    WaveOut1.Volume = 0.7f '70% Volume
    WaveOut2.Volume = 0.4f '40% Volume

    WaveOut1.Init(New Mp3FileReader("C:\Test1.mp3"))
    WaveOut2.Init(New Mp3FileReader("C:\Test2.mp3"))

    WaveOut1.Play()
    WaveOut2.Play()

End Sub
In future don´t spam, research yourself and as a last when nothing helped, ask precise and readable questions!

New Post: How to close an audio stream the right way to prevent it being in use on copy action

$
0
0
So I got my mlayer to work ( code below|)
But every time a play a file and stop it with
waveOut.Stop()
it appears to stay loaded in memory..
Because when i do a runtime copy action of the file...i get an error saying the file is in use by another program...etc. so somehow waveout.stop does not unload the file.
I could try waveout.dispose but that would prevent me from playing the file again afterwarts..since the waveout doesn't excist anymore.
so how to properly unload the mp3 files that where streaming?




'Declare on top:
Imports NAudio.Wave
Imports NAudio.Wave.SampleProviders
'Declare on top in class mainapp ( for my case)
Public waveOut As WaveOut = New WaveOut
Public WithEvents notify as NotifyingSampleProvider = Nothing
Public mp3Reader As Mp3FileReader = Nothing
Public conversionTick_ms As Decimal 'need this for slider

Public Sub Play_Sound(songname As String)
mp3Reader = New Mp3FileReader(songname)
notify = New NotifyingSampleProvider(mp3Reader.ToSampleProvider)

If waveOut.PlaybackState = PlaybackState.Playing Then
    waveOut.Stop()
    mp3Reader.Close()
Else
    waveOut.Init(Notify)
    waveOut.Play()
 conversionTick_ms = (mp3Reader.Position / mp3Reader.CurrentTime.TotalMilliseconds) 'need this for slider
End If
End Sub

'Use the notify event to update your playback position with each processed sample.
'This Event is the most accurate and fires at your Mp3FileReader´s samplerate (usually 44100 times per second).
'For performance reasons you should better count for some samples till update,
'or your Form will redraw the labels 44100 times per second (overkill cpu waste)

Private SampleCounter as Integer = 0
Private Sub notify_Sample(ByVal sender As Object, ByVal e As NAudio.Wave.SampleEventArgs) handles notify.Sample
SampleCounter += 1

'For example wait 1024 samples till updating again.
if SampleCounter >= 1024 then
 SampleCounter = 0

 'Current time:
 CurrentLenLabel.Text = New DateTime(mp3Reader.CurrentTime.Ticks).ToString("HH:mm:ss")

 'Total time:
 TotalLenLabel.Text = New DateTime(mp3Reader.TotalTime.Ticks).ToString("HH:mm:ss") 
'trackposition is the name of the slider(trackbar)
        TrackPosition.Minimum = 0
        TrackPosition.Maximum = mp3Reader.TotalTime.TotalMilliseconds
        TrackPosition.Value = mp3Reader.CurrentTime.TotalMilliseconds
End If
End Sub

'Than i added an event that runs when the position of the slider is changed manualy:
Private Sub Button6_Click_1(sender As Object, e As EventArgs) Handles Button6.Click
   'before changing the position of the mp3, convert milliseconds to ticks... 1ms is approx 176.4 ticks
    mp3Reader.Position = TrackPosition.Value * conversionTick_ms 
End Sub

Created Unassigned: Naudio and Unity for looping section [16494]

$
0
0
Hello - I got stuck trying to play a sound from my Unity Assets:


using UnityEngine;
using System.Collections;
using System;
using System.IO;
using NAudio;
using NAudio.Wave;

public class NaudioLooper : MonoBehaviour
{

public AudioClip asWs;

public class StartEndLoopReader{

public TimeSpan _start;
public TimeSpan _end;
public NAudio.Wave.WaveStream _stream;

public StartEndLoopReader(NAudio.Wave.WaveStream stream, TimeSpan start, TimeSpan end)
{
_stream = stream;
_stream.CurrentTime = start;
_start = start;
_end = end;
//return null;
}
}


void Start(){
TimeSpan _startInp =new TimeSpan (0, 0, 2);
TimeSpan _endInp = new TimeSpan (0, 0, 4);
NAudio.Wave.WaveStream _streamInp= new NAudio.Wave.WaveFileReader(@"Asset/Media/Tepotten_coolEditTilret 1w.wav");
NAudio.Wave.WaveOutEvent wo = new NAudio.Wave.WaveOutEvent();
StartEndLoopReader reader = new StartEndLoopReader( _streamInp, _startInp, _endInp);

wo.Init(reader);
wo.Play();
}

public int Read(byte[] array, int offset, int count)
{
Debug.Log(_stream.CurrentTime);
if (_stream.CurrentTime>_end)
{
// back to start to loop
// if you want to stop here, return 0 instead.
_stream.CurrentTime = _start;
}

return _stream.Read(array, offset, count);
}

#region IWaveProvider Members
public WaveFormat WaveFormat
{
get { return _stream.WaveFormat; }
}
#endregion
}


[its based on my workarounds from http://www.ceus-now.com/setting-playback-start-end-points-in-naudio/ ... where I (admit, quite in deperation) tried make StartEndLoopReader a class instead]

For now the "wo.Init(reader);" line causes me the biggest problems.
- what to do?

/best regards

New Post: How to close an audio stream the right way to prevent it being in use on copy action

$
0
0
it's the Mp3FileReader that needs disposing. WaveOut.Dispose will close the audio device.

New Post: Waveoutevent Player Auto Gain

$
0
0
Hi ,

I want Play all sound in same frequency . automatically calculate gain value pass the volume. Is it possible to this? Please help me to do very urgent requirements.

Thank You.

New Post: How to close an audio stream the right way to prevent it being in use on copy action

$
0
0
Thanks waveout.dispose did the trick

New Post: reading MP3v2 Tags and cover image

$
0
0
IS there a way to read the mp3tags , including the cover art? ( VB.net)
would like to retrieve the song name, artist, album and cover

New Post: reading MP3v2 Tags and cover image

$
0
0
not in NAudio I'm afraid. You should be able to find other libraries that can access metadata from MP3 files.

New Post: Prevent audio skip when recording during heavy system load.

$
0
0
Hi,

Have talked about this some years back i think.

But well when i am recording, even with 1000ms buffer with Wasapi,
if the system is under heavy load it will skip.

Now there are 2 solutions for this, one is making sure it doesn't skip (not sure if it can be done?).
Other is pushing out Silent data when audio is skipped to make up for the lost data (hence keeping to correct timeline).

So while the skipping is important to get rid of if possible, the most important thing is the timeline.

I know you can do this by using either the CPU QPC and sync to that clock, or use the Audio QPC and sync to that.
And by Sync i mean push silent data or remove data in order to keep the same time.

With Audio QPC it will most likely only be Pushing silent data though as it runs the same as the actual data anyway.

Problem with Audio QPC in my case is that one of them is an USB Device, and USB isn't hardware level, it's operated by CPU interruptions, so even whe Audio QPC can be affected by heavy load, though it's the data that first get affected, the QPC can survive a bit more.

CPU QPC is ideal in that sense as it's unaffected by load, problem is one needs to skip and push,
this would be great in my case as it would sync the audio during recording (sync to the PC clock which i need to do anyway).
Though one loses a bit of data rather than the resampling later way (not in the topic).


So i wonder what can be done?

I have played around A Lot with the idea, and while i have gotten it somewhat to work at times, it's never perfect and has issues.

Here is some of the code i played around with, was quite awhile ago so not sure what works as it's all commented out now.
But you can probably grasp the idea of what i am trying to do more or less (it's a mess).
        long DevicePosition, TimeQPC, LastQPC = 0, CurrentQPC = 0;
        int framesAvailable, CurrentSize = 0;
        public long getStartQPC() => LastQPC;
        public void setStartQPC(long d) => LastQPC = d;
        int recordsize = 0;
        int MSDiff = 0;
        bool first = false, test;
        int silence = 0;
        private void ReadNextPacket(AudioCaptureClient capture)
        {
            int packetSize = capture.GetNextPacketSize();
            int recordBufferOffset = 0;



            //Debug.WriteLine(string.Format("packet size: {0} samples", packetSize / 4));

            while (packetSize != 0)
            {


                AudioClientBufferFlags flags;

                IntPtr buffer = capture.GetBuffer(out framesAvailable, out flags, out DevicePosition, out TimeQPC);
                int bytesAvailable = framesAvailable * bytesPerFrame;
                if (!first)
                {
                    first = true;
                    CurrentSize -= framesAvailable;
                    LastQPC = TimeQPC;
                    CurrentSize += framesAvailable;
                    capture.ReleaseBuffer(framesAvailable);
                    packetSize = capture.GetNextPacketSize();
                    continue;
                }

                //recordsize += bytesAvailable + (recordBufferOffset);
                ////CurrentSize += framesAvailable;
                //CurrentQPC = (TimeQPC - LastQPC);
                //var QPCTime = TimeSpan.FromMilliseconds((CurrentQPC / 10000));
                //var DeviceTime = TimeSpan.FromMilliseconds(DevicePosition / (framesAvailable / 10));
                //var Time = TimeSpan.FromMilliseconds(CurrentSize / (framesAvailable / 10));

                //Debug.WriteLine("QPC: " + QPCTime + " - DevicePosition: " + DeviceTime + " - CurrentSize: " + Time);


                //var difference = (long)(QPCTime.TotalMilliseconds - DeviceTime.TotalMilliseconds);
                //if (difference < -10)
                //{

                //    Debug.WriteLine("Time: " + QPCTime);
                //    Debug.WriteLine("Skipped 10ms" + " - Total: " + MSDiff / -1 + "ms");
                //    recordsize -= recordBuffer.Length;
                //    recordBufferOffset += bytesAvailable;
                //    capture.ReleaseBuffer(framesAvailable);
                //    packetSize = capture.GetNextPacketSize();
                //    CurrentSize -= framesAvailable;
                //    continue;

                //}
                //else
                //if (difference > 10)
                //{
                //    recordsize += bytesAvailable + (recordBufferOffset);

                //    Debug.WriteLine("Add 10ms" + " - Total: " + MSDiff + "ms");
                //    MSDiff += 10;
                //    byte[] b = new byte[192 * (int)difference];
                //    silence += b.Length / 192;
                //    CurrentSize = ((int)Time.TotalMilliseconds + (int)difference) * (framesAvailable / 10);
                //    Debug.WriteLine("Silence: " + silence);
                //    DataAvailable(this, new WaveInEventArgs(b, b.Length));

                //    QPCTime = TimeSpan.FromMilliseconds((CurrentQPC / 10000));
                //    Time = TimeSpan.FromMilliseconds(CurrentSize / (framesAvailable / 10));
                //    difference = (long)(QPCTime.TotalMilliseconds - Time.TotalMilliseconds);
                //    Debug.WriteLine("QPC: " + QPCTime + " - DevicePosition: " + DeviceTime + " - CurrentSize: " + Time);
                //    Debug.WriteLine("Difference: " + difference);
                //    capture.ReleaseBuffer(framesAvailable);
                //    packetSize = capture.GetNextPacketSize();
                //    CurrentSize = ((int)QPCTime.TotalMilliseconds) * (framesAvailable * 10);
                //    return;

                //}

                // apparently it is sometimes possible to read more frames than we were expecting?
                // fix suggested by Michael Feld:
                int spaceRemaining = Math.Max(0, recordBuffer.Length - recordBufferOffset);
                if (spaceRemaining < bytesAvailable && recordBufferOffset > 0)
                {
                    if (DataAvailable != null) DataAvailable(this, new WaveInEventArgs(recordBuffer, recordBufferOffset));
                    recordBufferOffset = 0;
                }

                // if not silence...
                if ((flags & AudioClientBufferFlags.Silent) != AudioClientBufferFlags.Silent)
                {
                    Marshal.Copy(buffer, recordBuffer, recordBufferOffset, bytesAvailable);

                }
                else
                {

                    Array.Clear(recordBuffer, recordBufferOffset, bytesAvailable);
                }

                recordBufferOffset += bytesAvailable;
                capture.ReleaseBuffer(framesAvailable);
                    packetSize = capture.GetNextPacketSize();
                

                    if (DataAvailable != null)
                {
                    DataAvailable(this, new WaveInEventArgs(recordBuffer, bytesAvailable));
                }
            }
        }

New Post: Reading/Resampling a wav file to a byte array

$
0
0
I am attempting to use NAudio in a UWP. I would like to read a wav file and resample it into a 22050, 8-bit byte array.

Using your UWP demo, I added the following to your Load() method:
            CreateReader();
            byte[] wavByteArray = new byte[reader.Length];
            var result = reader.ReadAsync(wavByteArray, 0, (int)reader.Length);
When I select a file, it is picked correctly, and during the read, MediaFoundationReader.cs throws an exception. (bottom)

In the old 8.1 version of NAudio, I had used the MediaFoundationResampler, which I guess is not there anymore? Maybe there is some step I am missing to resample the incoming stream correctly?
using (var resampler = new MediaFoundationResampler(sourceProvider, waveformat) { ResamplerQuality = 60 }
Exception thrown is below:
System.InvalidCastException was unhandled by user code
  HResult=-2147467262
  Message=Unable to cast COM object of type 'System.__ComObject' to interface type 'NAudio.MediaFoundation.IMFSourceReader'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{70AE66F2-C809-4E4F-8915-BDCB406B7993}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
  Source=mscorlib
  StackTrace:
       at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)
       at NAudio.MediaFoundation.IMFSourceReader.ReadSample(Int32 dwStreamIndex, Int32 dwControlFlags, Int32& pdwActualStreamIndex, MF_SOURCE_READER_FLAG& pdwStreamFlags, UInt64& pllTimestamp, IMFSample& ppSample)
       at NAudio.Wave.MediaFoundationReader.Read(Byte[] buffer, Int32 offset, Int32 count)
       at System.IO.Stream.<>c.<BeginReadInternal>b__39_0(Object )
       at System.Threading.Tasks.Task`1.InnerInvoke()
       at System.Threading.Tasks.Task.Execute()
  InnerException: 

Created Unassigned: Bug...pin the reference to the callback delegate [16495]

$
0
0
NAudio is a great library! Thanks for sharing it.
A bug fix for your review.

See \naudio_38dadb417edc\NAudio\Wave\MmeInterop\WaveCallbackInfo.cs line 75
My fix is to pin the delegate used by the WinMM callback...

private static WaveInterop.WaveCallback reference; // pin the reference to the callback delegate.
// the CG may choose to clean up the "pointer to the function" as no one is using it!
// except that WinMM is!

internal MmResult WaveOutOpen(out IntPtr waveOutHandle, int deviceNumber, WaveFormat waveFormat, WaveInterop.WaveCallback callback)
{
reference = callback;

if (reference == null)
throw new ApplicationException("callback is null");

MmResult result;
if (Strategy == WaveCallbackStrategy.FunctionCallback)
{
result = WaveInterop.waveOutOpen(out waveOutHandle, (IntPtr)deviceNumber, waveFormat, callback, IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackFunction);
}
else
{
result = WaveInterop.waveOutOpenWindow(out waveOutHandle, (IntPtr)deviceNumber, waveFormat, this.Handle, IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackWindow);
}
return result;
}
I'm using your library in a "busy" .NET C# SDR application.

New Post: Reading/Resampling a wav file to a byte array

$
0
0
It might be a threading issue, I had a similar thing with the WMA Reader.

Alternatively, use WDL (WdlResamplingSampleProvider) to resample the audio.
Viewing all 5831 articles
Browse latest View live


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