4

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?

user1992705
  • 188
  • 1
  • 3
  • 8
  • If "in parallel" actually means "start at the exact same time so the user cannot tell the difference" then no, you'll never get that to work. The human ear is extremely sensitive to timing differences, tells it where the lion is located. – Hans Passant Jan 19 '13 at 12:39
  • While what Hans wrote is true, with DirectShow API if you time stamp data correctly and accurately on parallel streams, it is possible to achieve perfect mixing too. – Roman R. Jan 19 '13 at 12:41

3 Answers3

0

Take a look at the NAudio library.

For playing multiple files at the same time, see this post.

Flagbug
  • 2,093
  • 3
  • 24
  • 47
0

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.

Roman R.
  • 68,205
  • 6
  • 94
  • 158
0

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.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98