How to play audio file in C# with low latency/very little delay in C#?

天涯浪子 提交于 2019-12-12 18:00:49

问题


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?


回答1:


Take a look at the NAudio library.

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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/14414271/how-to-play-audio-file-in-c-sharp-with-low-latency-very-little-delay-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!