简体   繁体   中英

C# Set duration and play sounds stored in an arraylist consecutively

I have the following Play method for playing musical notes stored in an arraylist:

public void Play(Duration d){


            int duration = 1;

            if (d == Duration.SemiBreve)
            {
                duration = 16;
            }

            else if (d == Duration.DotMin)
            {
                duration = 10;
            }

            else if (d == Duration.minim)
            {
                duration = 8;
            }

            else if (d == Duration.Crotchet)
            {
                duration = 4;
            }

            else if (d == Duration.Quaver)
            {
                duration = 2;
            }

            else if (d == Duration.SemiQuaver)
            {
                duration = 1;
            }

            player = new SoundPlayer();

            player.SoundLocation = "pathToLocation";


            //set timer
            time = new Timer();
            time.Tick += new EventHandler(clockTick);
            time.Interval = duration * 150;
            player.Play();
            time.Start();

        }

When I call the method with a button:

private void PlayButton_Click(object sender, EventArgs e)

{

        //Loops through the collection and plays each note one after the other
        foreach (MusicNote music in this.staff.Notes)
        {
            music.Play(music.Dur)

        }
    }

Only the last note gets played. With PlaySync() all the notes get played but the duration isn't recognized. I also tried using threads like so:

foreach (MusicNote music in this.staff.Notes)
            {
                Thread t = new Thread(playMethod=>music.Play(music.Dur));  
                t.Start();
                t.Join();

            }

But it doesn't work either. Any suggestions as to how I can get the files to play consecutively like with PlaySync but using their set duration?

You don't wait for the timer anywhere. So in practice all notes get played almost simultaneously, causing just the last one to be effectively audible.


UPDATE: Using the System.Timers.Timer class the way to go is registering a handler for the Elapsed event and playing the notes one-by-one in the event handler. This way you avoid freezing the UI.

Another option is playing in a background thread and the using Thread.Sleep to wait. Here you will have to make sure the thread is stopped according to the state of the UI (ie the use closes the current dialog etc.).

In either case to avoid race conditions you will have to solve concurrent access to staff.Notes or make a copy of it for the sake of playing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM