C#使用SoundPlayer暂停和恢复

时间:2013-11-04 06:32:19

标签: c# audio

我是另一个涉及C#的人,想要创建一个简单的音频应用程序,通过上传程序播放加载到程序中的wav文件。我的问题是当我通过我的播放按钮再次启动音频文件时,我需要获取正在播放的任何音频文件以暂停使用音频文件的音轨计时器。我已经有了一个全局计时器'baseTimer',我认为我可以使用它来设置音频文件,已停止,跟踪持续时间点。但是我不知道如何完成这个,也不知道如何使用所有mci命令。

我已经显示了我的主要应用程序的所有代码...我也读过我可能需要使用线程,但我也读过用线程设置音频文件跟踪持续时间是不可能的

public partial class FrmMain : Form
{
    public FrmMain()
    {
        InitializeComponent();
    }

    System.Timers.Timer baseTimer = new System.Timers.Timer();

    List<string> PlayList = new List<string>();
    List<byte> PlayList_byte;
    int soundNum = 0;

    private string music_PATH { get; set; }
    private string talk_PATH { get; set; }
    private byte Pause_TIME { get; set; }
    private string Pause_RADIO { get; set; }

    bool isStopped = new bool();
    bool isPaused = new bool();

    [DllImport("winmm.dll")]
    private static extern uint mciSendString(string command, StringBuilder returnValue, int returnLength, IntPtr winHandle);

    public static int GetSoundLength(string fileName)
    {
        StringBuilder lengthBuf = new StringBuilder(32);

        mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
        mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
        mciSendString("close wave", null, 0, IntPtr.Zero);

        int length = 0;
        int.TryParse(lengthBuf.ToString(), out length);

        return length;
    }

    private void SetPath()
    {
        music_PATH = @"..\\..\\commercial\list.txt";
        talk_PATH = @"..\\..\\main\list.txt";
        StreamReader myReader;

        using (myReader = new StreamReader(music_PATH))
        {
            while (myReader.Peek() != -1)
            {
                string read = myReader.ReadLine();
                PlayList.Add(read);
            }
        }

        using (myReader = new StreamReader(talk_PATH))
        {
            while (myReader.Peek() != -1)
            {
                string read = myReader.ReadLine();
                PlayList.Add(read);
            }
            myReader.Close();
        }

        foreach (string sound in PlayList)
        {
            soundNum++;
        }
    }

    private string CurrentSound()
    {
        try
        {
            Random _randx = new Random();
            int pick = _randx.Next(0, soundNum);

            string currentaudio = PlayList[pick];
            Pause_RADIO = currentaudio;
            return currentaudio;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
        return null;
    }

    string _SelectedSound = "";

    private string _Sound(string currentradio, string pattern)
    {
        foreach (Match entry in Regex.Matches(currentradio, pattern))
        {
            _SelectedSound = entry.Value.ToString();
        }
        if (_SelectedSound == "music")
        {
            return "commercial";
        }
        else if (_SelectedSound == "talk")
        {
            return "main";
        }
        return null;
    }

    private void _SetTimer(string currentradio, string pattern)
    {
        baseTimer.Interval = GetSoundLength(@"..\\..\\" + pattern + @"\" + currentradio);
    }

    private bool isRepeat(string lastradio, string currentradio)
    {
        if (lastradio == currentradio)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private void baseTimerElasped(object sender, ElapsedEventArgs e)
    {
        Radio.FrmMain play = new Radio.FrmMain();
        play.PlayPlayer();
    }

    private void PlayPlayer()
    {
        MediaPlayer wavplayer;
        try
        {
            if (soundNum == 0)
            {
                SetPath();
                PlayPlayer();
            }
            else
            {
                string currentradio = CurrentSound();
                bool localcheck = isRepeat(_SelectedSound, currentradio);
                if (localcheck == true)
                {
                    PlayPlayer();
                }
                else
                {
                    string Pattern = @"(music|talk)";
                    string selected = _Sound(currentradio, Pattern);
                    _SetTimer(currentradio, selected);

                    switch (selected)
                    {
                        case "commercial":
                            music_PATH = @"..\\..\\commercial\";
                            PlayList_byte = new List<byte>(File.ReadAllBytes(music_PATH + currentradio));
                            wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
                            wavplayer.Play();
                            baseTimer.Start();
                            break;
                        case "main":
                            talk_PATH = @"..\\..\\main\";
                            PlayList_byte = new List<byte>(File.ReadAllBytes(talk_PATH + currentradio));
                            wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
                            wavplayer.Play();
                            baseTimer.Start();
                            break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message + ex.StackTrace + ex.Source);
        }
    }

    private void PausePlayer()
    {
        MediaPlayer wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
        baseTimer.Stop();

        MessageBox.Show("Count: " + PlayList_byte.Count + "Pause_TIME: " + Pause_TIME + "\nPlaylist_byte" + PlayList_byte.ToString());

        try
        {
            switch (isPaused)
            {
                case false:
                    isPaused = true;
                    wavplayer.Stop();
                    break;
                case true:
                    isPaused = false;
                    string localcheck = _Sound(Pause_RADIO, @"(music|talk)");
                    switch (localcheck)
                    {
                        case "commercial":
                            music_PATH = @"..\\..\\commercial\";
                            wavplayer.Play(PlayList_byte.GetRange(PlayList_byte.Count - Pause_TIME, PlayList_byte.Count - Pause_TIME).ToArray());
                            break;
                        case "main":
                            talk_PATH = @"..\\..\\main\";
                            wavplayer.Play(PlayList_byte.GetRange(PlayList_byte.Count - Pause_TIME, PlayList_byte.Count - Pause_TIME).ToArray());
                            break;
                    }
                    break;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message + ex.Data);
        }
    }

    private void btnPlay_Click(object sender, EventArgs e)
    {
        switch (isStopped)
        {
            case false:
                isStopped = true;
                btnPlay.Image = Image.FromFile(@"..\\..\\Pause.png");
                lblPlay.Text = "Pause";
                if (isPaused == false)
                {
                    PlayPlayer();
                }
                else
                {
                    PausePlayer();
                }
                break;
            case true:
                isStopped = false;
                btnPlay.Image = Image.FromFile(@"..\\..\\Play.png");
                lblPlay.Text = "Play";
                PausePlayer();
                break;
        }

        baseTimer.Elapsed += new ElapsedEventHandler(baseTimerElasped);
    }

    private void btnNext_Click(object sender, EventArgs e)
    {
        PlayPlayer();
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        MediaPlayer wavplayer = new MediaPlayer();
        wavplayer.Stop();
        baseTimer.Stop();
    }

    private void btnQuit_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void btnGetUpload_Click(object sender, EventArgs e)
    {
        Uploader FrmUpload = new Uploader();
        FrmUpload.Show();
        this.Hide();
    }
}
class MediaPlayer
{
    SoundPlayer wavplayer;

    public MediaPlayer()
    {
        Stop();
    }

    public MediaPlayer(byte[] buffer)
    {
        MemoryStream memStream = new MemoryStream(buffer, true);
        wavplayer = new SoundPlayer(memStream);
    }

    public void Play()
    {
        wavplayer.Play();
    }

    public void Play(byte[] buffer)
    {
        wavplayer.Stream.Seek(0, SeekOrigin.Begin);
        wavplayer.Stream.Write(buffer, 0, buffer.Length);
        wavplayer.Play();
    }

    public void Stop()
    {
        wavplayer.Stop();
    }
}

编辑:

为了清楚起见,currentaudio有一个文件,如“music3.wav”或“talk1.wav”。

2 个答案:

答案 0 :(得分:0)

SoundPlayer非常有限,不支持暂停和恢复。您是否可以使用WPF MediaElement代替?您会发现它功能更强大,支持播放多种类型的文件,重新定位,设置音量,暂停和恢复。您也可以使用它来获取文件长度而不是mci。

答案 1 :(得分:0)

非常老的问题,但对于任何看这里的人来说,这对我有用:

double currentPos = audioplayer.CurrentPosition;
audioplayer.Play();
audioplayer.Seek(currentPos);