How to play a music file for a specified amount of time

独自空忆成欢 提交于 2019-12-11 02:44:48

问题


What I'm trying to do is play a music file for a specified duration, and then stop playing. However, the whole music file is being played. Any ideas?

I've tried starting a new thread, still doesnt work.


回答1:


The problem is that PlaySync blocks the thread, so other messages won't be processed. This includes your stop command from the Tick event. You have to use the regular Play function, which will be asynchronous and creates a new thread to play the file in. You will have to handle the resulting multithreading situation depending on how your application works.




回答2:


I would build something approximately like this: It is just written out of hand in the edit window so don't expect it to compile just like that. It is only meant to illustrate the idea.

internal class MusicPlayer
{
    private const int duration = 1000;
    private Queue<string> queue;
    private SoundPlayer soundPlayer;
    private Timer timer;

    public MusicPlayer(params object[] filenames)
    {
        this.queue = new Queue<string>();
        foreach (var filenameObject in filenames)
        {
            var filename = filenameObject.ToString();
            if (File.Exists(filename))
            {
                this.queue.Enqueue(filename);
            }
        }

        this.soundPlayer = new SoundPlayer();
        this.timer = new Timer();
        timer.Elapsed += new System.Timers.ElapsedEventHandler(ClockTick);
    }

    public event EventHandler OnDonePlaying;

    public void PlayAll()
    {
        this.PlayNext();
    }

    private void PlayNext()
    {
        this.timer.Stop();
        var filename = this.queue.Dequeue();
        this.soundPlayer.SoundLocation = filename;
        this.soundPlayer.Play();
        this.timer.Interval = duration;
        this.timer.Start();
    }

    private void ClockTick(object sender, EventArgs e)
    {
        if (queue.Count == 0 ) {
            this.soundPlayer.Stop();
            this.timer.Stop();
            if (this.OnDonePlaying != null)
            {
                this.OnDonePlaying.Invoke(this, new EventArgs());
            }
        }
        else 
        {
            this.PlayNext();
        }
    }
}



回答3:


try this:

ThreadPool.QueueUserWorkItem(o => {
                                    note.Play();
                                    Thread.Sleep(1000);
                                    note.Stop();
                                   });


来源:https://stackoverflow.com/questions/8531789/how-to-play-a-music-file-for-a-specified-amount-of-time

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