Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
799 views
in Technique[技术] by (71.8m points)

c# - How to detect when a mp3 file has finished playing

My c# windows form is enable to play an mp3 file.I did this using this code

    WMPLib.WindowsMediaPlayer wplayer;
    wplayer = new WMPLib.WindowsMediaPlayer();
    wplayer.URL = "c:/Standup.mp3";
    wplayer.controls.play();

this works perfectly but i want to know when the file has finished playing so that i can restart it.

Pls how do i do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it by using the PlayStateChanged event. you can add it to your MediaPlayer like this.

WMPLib.WindowsMediaPlayer wplayer;
wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(wplayer_PlayStateChange);
wplayer.URL = "c:/Standup.mp3";
wplayer.controls.play();

you can then check for the MediaEnded PlayState in the EventHandler and reset the currentPosition to the start of the song :

void wplayer_PlayStateChange(int NewState)
{
    if (NewState == (int)WMPLib.WMPPlayState.wmppsMediaEnded)
    {
        wplayer.controls.currentPosition = 0;
    }
}

Edit: I expected to be able to make a song repeatable to the point I was sick of it, and the above code did work when I had breakpoints set. Once I removed them I found there were other PlayStates that were stopping the file from being played. I was able to bypass it by using a one shot timer.. Now I am tired of the song that I was using. There may/probably be a better way of doing this, but this will work.

Modified Code

public partial class Form1 : Form
{
    WMPLib.WindowsMediaPlayer wplayer;
    Timer tmr = new Timer();
    public Form1()
    {
        InitializeComponent();
        tmr.Interval = 10;
        tmr.Stop();
        tmr.Tick += new EventHandler(tmr_Tick);
        wplayer = new WMPLib.WindowsMediaPlayer();
        wplayer.URL = "c:/Standup.mp3";
        wplayer.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(wplayer_PlayStateChange);
        wplayer.controls.play();
    }

    void tmr_Tick(object sender, EventArgs e)
    {
        tmr.Stop();
        wplayer.controls.play();
    }

    void wplayer_PlayStateChange(int NewState)
    {
        if (NewState == (int)WMPLib.WMPPlayState.wmppsMediaEnded )
        {
            tmr.Start();

        }
    }


}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...