Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / C#

C# MIDI Toolkit

Rate me:
Please Sign up or sign in to vote.
4.95/5 (177 votes)
18 Apr 2007MIT18 min read 3.2M   41.8K   303  
A toolkit for creating MIDI applications with C#.
/*
 * Created by: Leslie Sanford
 * 
 * Contact: jabberdabber@hotmail.com
 * 
 * Last modified: 09/27/2004
 */

using System;
using System.Collections;

namespace Multimedia.Midi
{

	/// <summary>
	/// Handles playback of a sequence.
	/// </summary>
	internal sealed class SequencePlayer : IDisposable
	{
        #region SequencePlayer Members

        #region Fields

        // The list of track players.
        private ArrayList trackPlayers = new ArrayList();

        // The number of tracks currently soloed.
        private int soloCount = 0;

        // The number of tracks currently playing.
        private int activeTrackCount;

        #endregion

        #region Events

        /// <summary>
        /// Occurs when the end of the sequence has been reached.
        /// </summary>
        public event EventHandler EndOfSequenceReached;

        #endregion

        #region Construction

        /// <summary>
        /// Initializes a new instance of the SequencePlayer class with the 
        /// specified MIDI sender, tick generator and sequence.
        /// </summary>
        /// <param name="midiSender">
        /// The MIDI sender to use to send MIDI messages.
        /// </param>
        /// <param name="tickGen">
        /// The tick generator used for timing the playback of MIDI messages.
        /// </param>
        /// <param name="seq">
        /// The sequence to playback.
        /// </param>
		public SequencePlayer(IMidiSender midiSender, TickGenerator tickGen, 
            Sequence seq)
		{
            // For each track in the sequence.
            foreach(Track t in seq)
            {
                // Create track player for the track.
                TrackPlayer player = new TrackPlayer(midiSender, tickGen, t);
                trackPlayers.Add(player);

                // Register to be notified when the track player has reached 
                // the end of the track.
                player.EndOfTrackReached += 
                    new EventHandler(EndOfTrackReachedHandler);
            }

            activeTrackCount = trackPlayers.Count;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Turns all currently sounding notes off.
        /// </summary>
        public void AllSoundsOff()
        {
            foreach(TrackPlayer player in trackPlayers)
                player.AllSoundsOff();
        }

        /// <summary>
        /// Seeks a position within the sequence.
        /// </summary>
        /// <param name="position">
        /// The position in ticks to seek.
        /// </param>
        public void Seek(int position)
        {
            // Reset the active track count.
            activeTrackCount = trackPlayers.Count;

            // Seek position for each track player.
            foreach(TrackPlayer player in trackPlayers)
                player.Seek(position);
        }

        /// <summary>
        /// Sets the mute state of a track.
        /// </summary>
        /// <param name="index">
        /// Index into the sequence of the track to solo.
        /// </param>
        /// <param name="mute">
        /// A value indicating whether or not to mute the track.
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown if the track index is out of range.
        /// </exception>
        public void MuteTrack(int index, bool mute)
        {
            // Enforce preconditions.
            if(index < 0 || index >= trackPlayers.Count)
                throw new ArgumentOutOfRangeException("index", index,
                    "Track index out of range.");

            ((TrackPlayer)trackPlayers[index]).Mute = mute;
        }

        /// <summary>
        /// Sets the solo state of a track.
        /// </summary>
        /// <param name="index">
        /// Index into the sequence of the track to solo.
        /// </param>
        /// <param name="solo">
        /// A value indicating whether or not to solo the track.
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown if the track index is out of range.
        /// </exception>
        public void SoloTrack(int index, bool solo)
        {
            // Enforce preconditions.
            if(index < 0 || index >= trackPlayers.Count)
                throw new ArgumentOutOfRangeException("index", index,
                    "Track index out of range.");

            // Get the track player responsible for the track at the specified
            // index.
            TrackPlayer player = (TrackPlayer)trackPlayers[index];

            // Guard.
            if(player.Solo == solo)
                return;

            // Set solo value.
            player.Solo = solo;

            // If the track is being soloed.
            if(solo)
            {
                // If no tracks have been soloed so far.
                if(soloCount == 0)
                {
                    // For each track player, enable solo mode and turn off all
                    // sounds of those tracks not soloed.
                    foreach(TrackPlayer p in trackPlayers)
                    {
                        p.SoloModeEnabled = true;

                        if(!p.Solo)
                            p.AllSoundsOff();
                    }
                }

                // Keep track of the number of tracks soloed.
                soloCount++;
            }
            // Else the track is not being soloed.
            else
            {
                // Keep track of the number of tracks soloed.
                soloCount--;

                // If no tracks are soloed, disable the solo mode of each track
                // player.
                if(soloCount == 0)
                    foreach(TrackPlayer p in trackPlayers)
                        p.SoloModeEnabled = false;
            }
        }

        /// <summary>
        /// Keeps track of how many tracks are still playing.
        /// </summary>
        /// <param name="sender">
        /// The track responsible for triggering the event.
        /// </param>
        /// <param name="e">
        /// Information about the event.
        /// </param>
        private void EndOfTrackReachedHandler(object sender, EventArgs e)
        {
            // One less track is now playing.
            activeTrackCount--;

            // If there are no more tracks playing, raise end of sequence 
            // event.
            if(activeTrackCount == 0)
                OnEndOfSequenceReached();
        }

        /// <summary>
        /// Raises the end of sequence event.
        /// </summary>
        private void OnEndOfSequenceReached()
        {
            if(EndOfSequenceReached != null)
                EndOfSequenceReached(this, EventArgs.Empty);
        }

        #endregion

        #endregion

        #region IDisposable Members

        /// <summary>
        /// Disposes of the sequence player.
        /// </summary>
        public void Dispose()
        {
            foreach(TrackPlayer player in trackPlayers)
            {
                player.EndOfTrackReached -= new EventHandler(EndOfTrackReachedHandler);
                player.Dispose();
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
United States United States
Aside from dabbling in BASIC on his old Atari 1040ST years ago, Leslie's programming experience didn't really begin until he discovered the Internet in the late 90s. There he found a treasure trove of information about two of his favorite interests: MIDI and sound synthesis.

After spending a good deal of time calculating formulas he found on the Internet for creating new sounds by hand, he decided that an easier way would be to program the computer to do the work for him. This led him to learn C. He discovered that beyond using programming as a tool for synthesizing sound, he loved programming in and of itself.

Eventually he taught himself C++ and C#, and along the way he immersed himself in the ideas of object oriented programming. Like many of us, he gotten bitten by the design patterns bug and a copy of GOF is never far from his hands.

Now his primary interest is in creating a complete MIDI toolkit using the C# language. He hopes to create something that will become an indispensable tool for those wanting to write MIDI applications for the .NET framework.

Besides programming, his other interests are photography and playing his Les Paul guitars.

Comments and Discussions