How do I play an audio file(.mp3) in C# with very little delay? What I mean is, the file should start playing the right after user input is provided and later than that.
Also, how can I play two audio files in parallel at the same time?
How do I play an audio file(.mp3) in C# with very little delay? What I mean is, the file should start playing the right after user input is provided and later than that.
Also, how can I play two audio files in parallel at the same time?
To get minimally possible delay you need audio playback running with with no/silence data and on the event of interest you will supply real playback data onto already active device. This way you eliminate overhead of activating audio playback device that might be possibly taking place. The overhead is not that large, so you might prefer to not overcomplicate your app.
There is a choice of APIs to play audio: DirectShow.NET, NAudio in particular.
Unless you are going to work with playback device in exclusive mode (which you are unlikely to want to do), all the APIs support playback of multiple independent streams and all mixing is done for you automatically behind the scene.
I show you how I do this using DirectX AudioVideoPlayback:
public class MusicPlayer
{
private static Audio m_Audio;
private static void Loop(Object Sender, EventArgs e)
{
((Audio)Sender).SeekCurrentPosition(0d, SeekPositionFlags.AbsolutePositioning);
}
public static void Dispose()
{
if (m_Audio != null)
{
m_Audio.Stop();
m_Audio.Dispose();
m_Audio = null;
}
}
public static void Mute()
{
if ((m_Audio != null) && m_Audio.Playing)
m_Audio.Volume = -10000;
}
public static void Play(String filePath, Boolean loop)
{
if (File.Exists(filePath))
{
Dispose();
if (m_Audio == null)
m_Audio = new Audio(filePath);
else
m_Audio.Open(filePath);
if (loop)
m_Audio.Ending += Loop;
m_Audio.Volume = MusicSettings.Volume - 10000;
m_Audio.Play();
}
}
public static void Unmute()
{
if (m_Audio != null)
m_Audio.Volume = MusicSettings.Value - 10000;
}
}
You can start from this snippet.