Archive

Posts Tagged ‘irrKlang’

Playing MP3 from C#

March 1, 2011 9 comments

After handling a huge collections of MP3 files, one in my back-up drive and another in my hard-disk’s library, It meant huge gobbling up so much space, which of course you realize when your external hard-drive shows up “Drive Full” message. And an idea bloomed to create this mp3 player which plays files stored in my database!

I have named it “Byte Player” and according to the name the application would be playing the music when data is fed into as byte arrays. The database is designed using the same strategy that’s designed to store normal files.

Add the following DLL reference: “irrKlang.NET4” and put the following DLLs to your bin folder:
~ ikpFlac.dll
~ ikpMP3.dll
~ irrKlang.NET4.dll

Use the following reference:

using IrrKlang;

Generated Database Script to Create Table:

CREATE TABLE [dbo].[MusicLibrary](
	[FileID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[FileName] [nvarchar](50) NOT NULL,
	[FileContent] [varbinary](max) NOT NULL,
	[FileType] [nvarchar](50) NOT NULL,
	[CreateBy] [nvarchar](128) NULL,
	[CreatedOn] [datetime] NULL,
	[ModifiedBy] [nvarchar](128) NULL,
	[ModifiedOn] [datetime] NULL,
 CONSTRAINT [PK_MusicLibrary] PRIMARY KEY CLUSTERED 
(
	[FileID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_FileID]  DEFAULT (newid()) FOR [FileID]
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_CreateBy]  DEFAULT (user_name(user_id(user_name()))) FOR [CreateBy]
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_CreatedOn]  DEFAULT (getdate()) FOR [CreatedOn]
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_ModifiedBy]  DEFAULT (user_name(user_id(user_name()))) FOR [ModifiedBy]
GO

ALTER TABLE [dbo].[MusicLibrary] ADD  CONSTRAINT [DF_MusicLibrary_ModifiedOn]  DEFAULT (getdate()) FOR [ModifiedOn]
GO

The C# application will hold the following methods to interact with the database.

const string connectionString = @"Server=KRISHNA\SQLEXPRESS;Database=music;Trusted_Connection=True;";

/// <summary>
/// Function to select files from the computer to be saved in the database.
/// </summary>
private void OpenMP3Files()
{
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.Filter = "MP3 files|*.mp3";
    dialog.FilterIndex = 1;
    dialog.InitialDirectory = @"C:\\";
    dialog.RestoreDirectory = true;
    dialog.CheckFileExists = true;
    dialog.CheckPathExists = true;
    dialog.Multiselect = true;
    if (dialog.ShowDialog() == DialogResult.OK)
    {
        Cursor.Current = Cursors.WaitCursor;
        foreach (string filename in dialog.FileNames)
        {
            FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
            using (BinaryReader reader = new BinaryReader(stream))
            {
                long length = new FileInfo(filename).Length;
                InsertMP3File(Path.GetFileName(filename), reader.ReadBytes((int)length));
            }
        }
        GetAllMP3();
    }
}

/// <summary>
/// Retrieves entire MP3 list from database (excludes the file content)
/// </summary>
private void GetAllMP3()
{
    string queryString = "SELECT [FileID], [FileName] FROM [MusicLibrary]";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = new SqlCommand(queryString, connection);
        DataSet dataset = new DataSet();
        adapter.Fill(dataset);
        if (dataset.Tables.Count > 0)
        {
            gridMusic.DataSource = dataset.Tables[0];
            gridMusic.Columns[0].Visible = false;
            gridMusic.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
    }
}

/// <summary>
/// Individual files are stored in the database.
/// </summary>
/// <param name="filename"></param>
/// <param name="data"></param>
private void InsertMP3File(string filename, byte[] data)
{
    string filetype = @"audio / mpeg";
    string queryString = "INSERT INTO [MusicLibrary] ([FileName] ,[FileContent] ,[FileType]) VALUES (@FileName, @FileContent, @FileType)";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Parameters.Add(new SqlParameter("@FileName", (object)filename));
        command.Parameters.Add(new SqlParameter("@FileContent", (object)data));
        command.Parameters.Add(new SqlParameter("@FileType", (object)filetype));
        command.Connection.Open();
        command.ExecuteNonQuery();
        command.Connection.Close();
    }
}

Inorder to play the MP3 file I had some initial consideration and based on some strong reviews started of with the “NAudio” library [Ref: http://naudio.codeplex.com] but i faced some issues while trying to play the file from stream and upon searching through discussion forums I discovered that these issues are currently being worked upon and would have a fix in future releases; Therefore i was forced to consider my second choice “irrKlang” sound library [Ref: http://www.ambiera.com/irrklang/] and it worked out to be more simple and brilliant! The code illustrated below shows the fine integration between this library api and the database.

const string sound = "static.mp3";
ISoundEngine engine = new ISoundEngine();

/// <summary>
/// Retrieve individual file content from database
/// </summary>
/// <param name="fileID"></param>
private void GetMP3Data(string fileID)
{
    string queryString = "SELECT [FileContent] FROM [MusicLibrary] WHERE [FileID] = @FileID";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new System.Data.SqlClient.SqlCommand(queryString, connection);
        command.Parameters.Add(new SqlParameter("@FileID", (object)fileID));
        command.Connection.Open();
        byte[] buffer = (byte[])command.ExecuteScalar();
        if (engine.IsCurrentlyPlaying(sound))
        {
            engine.RemoveAllSoundSources();
        }
        PlayMP3(buffer, sound);
        command.Connection.Close();
    }
}

/// <summary>
/// Play a single MP3 file
/// </summary>
/// <param name="data"></param>
/// <param name="filename"></param>
private void PlayMP3(byte[] data, string filename)
{
    ISoundSource source = engine.AddSoundSourceFromMemory(data, filename);
    engine.Play2D(filename);
}

I am so much interested in improving this and building a full-fledged player that would support right from ripping CD’s and expanding the database to include more information about the music albums and MP3 tags.

Categories: C#, Database Tags: , , , ,