Click here to Skip to main content
Click here to Skip to main content

MP3 + CDG Karaoke Player

, 25 Jun 2010
Rate this:
Please Sign up or sign in to vote.
MP3 and CDG file player.

Introduction

This is an MP3 + CDG file player application that parses CDG files and renders them in real time while an MP3 file is played. As a bonus, I included an MP3 + CDG to AVI conversion application which will not be discussed in this article.

Background

After looking on the web for a while, I noticed that there was no .NET implementation for CDG file parsing available. One thing led to another, and I started porting over some C++ code that I found on Google Code. Once playback was established, I wanted pitch shifting. After that, I wanted rendering to AVI files. After that, I wanted transparency and background video for the AVI rendering...

Using the Code

This is the high level workflow for playing MP3 and CDG files together:

  1. Unzip the MP3 and CDG files into a temporary directory.
  2. Create a stream and open the CDG file.
  3. Determine the duration of the CDG file so that boundaries can be defined.
  4. Start playback of the MP3 file.
  5. Render the frame of the CDG file that is at the elapsed time position of the MP3 that is playing.

The main playback rendering block looks like this:

Private Sub Play()
    Try
      If mMP3Stream <> 0 AndAlso Bass.BASS_ChannelIsActive(mMP3Stream) = _
                    BASSActive.BASS_ACTIVE_PLAYING Then
        StopPlayback()
      End If
      PreProcessFiles()
      If mCDGFileName = "" Or mMP3FileName = "" Then
        MsgBox("Cannot find a CDG and MP3 file to play together.")
        StopPlayback()
        Exit Sub
      End If
      mPaused = False
      mStop = False
      mFrameCount = 0
      mCDGFile = New CDGFile(mCDGFileName)
      Dim cdgLength As Long = mCDGFile.getTotalDuration
      PlayMP3Bass(mMP3FileName)
      Dim startTime As DateTime = Now
      Dim endTime = startTime.AddMilliseconds(mCDGFile.getTotalDuration)
      Dim millisecondsRemaining As Long = cdgLength
      While millisecondsRemaining > 0
        If mStop Then
          Exit While
        End If
        millisecondsRemaining = endTime.Subtract(Now).TotalMilliseconds
        Dim pos As Long = cdgLength - millisecondsRemaining
        While mPaused
          endTime = Now.AddMilliseconds(millisecondsRemaining)
          Application.DoEvents()
        End While
        mCDGFile.renderAtPosition(pos)
        mFrameCount += 1
        mCDGWindow.PictureBox1.Image = mCDGFile.RGBImage
        mCDGWindow.PictureBox1.BackColor = CType(mCDGFile.RGBImage, Bitmap).GetPixel(1, 1)
        mCDGWindow.PictureBox1.Refresh()
        Dim myFrameRate As Single = Math.Round(mFrameCount / (pos / 1000), 1)
        Application.DoEvents()
      End While
      StopPlayback()
    Catch ex As Exception
    End Try
End Sub

Another challenge that presented itself was taking a multidimensional array of integers that was created from the CDG library and converting it into a bitmap. Here is the code that does the conversion:

Public ReadOnly Property RGBImage(Optional ByVal makeTransparent _
                As Boolean = False) As System.Drawing.Image
    Get
      Dim temp As New MemoryStream
      Try
        Dim i As Integer = 0
        For ri = 0 To CDG_FULL_HEIGHT - 1
          For ci = 0 To CDG_FULL_WIDTH - 1
            Dim ARGBInt As Integer = m_pSurface.rgbData(ri, ci)
            Dim myByte(3) As Byte
            myByte = BitConverter.GetBytes(ARGBInt)
            temp.Write(myByte, 0, 4)
          Next
        Next
      Catch ex As Exception
        'Do nothing (empty bitmap will be returned)
      End Try
      Dim myBitmap As Bitmap = StreamToBitmap(temp, CDG_FULL_WIDTH, CDG_FULL_HEIGHT)
      If makeTransparent Then
        myBitmap.MakeTransparent(myBitmap.GetPixel(1, 1))
      End If
      Return myBitmap
  End Get
End Property

Public Shared Function StreamToBitmap(ByRef stream As Stream, _
              ByVal width As Integer, ByVal height As Integer) As Bitmap
    'create a new bitmap
    Dim bmp As New Bitmap(width, height, PixelFormat.Format32bppArgb)
    Dim bmpData As BitmapData = bmp.LockBits(New Rectangle(0, 0, width, height), _
                                ImageLockMode.[WriteOnly], bmp.PixelFormat)
    stream.Seek(0, SeekOrigin.Begin)
    'copy the stream of pixel
    For n As Integer = 0 To stream.Length - 1
      Dim myByte(0) As Byte
      stream.Read(myByte, 0, 1)
      Marshal.WriteByte(bmpData.Scan0, n, myByte(0))
    Next
    bmp.UnlockBits(bmpData)
    Return bmp
End Function

The BASS Sound library was used for playback so the pitch of the MP3 could be changed in real time to adjust to the singer's key. Volume control was also needed to be able to mix volume levels from the MP3 with the singer's microphone. Here is the code that allows for the playback, volume control, and real-time pitch shifting:

Private Sub PlayMP3Bass(ByVal mp3FileName As String)
    If mBassInitalized OrElse Bass.BASS_Init(-1, 44100, _
                       BASSInit.BASS_DEVICE_DEFAULT, Me.Handle) Then
      mMP3Stream = 0
      mMP3Stream = Bass.BASS_StreamCreateFile(mp3FileName, 0, 0, _
                   BASSFlag.BASS_STREAM_DECODE Or _
                   BASSFlag.BASS_SAMPLE_FLOAT Or BASSFlag.BASS_STREAM_PRESCAN)
      mMP3Stream = AddOn.Fx.BassFx.BASS_FX_TempoCreate(mMP3Stream, _
                   BASSFlag.BASS_FX_FREESOURCE Or BASSFlag.BASS_SAMPLE_FLOAT _
                   Or BASSFlag.BASS_SAMPLE_LOOP)
      If mMP3Stream <> 0 Then
        AdjustPitch()
        AdjustVolume()
        ShowCDGWindow()
        Bass.BASS_ChannelPlay(mMP3Stream, False)
      Else
        Throw New Exception(String.Format("Stream error: {0}", _
                            Bass.BASS_ErrorGetCode()))
      End If
    End If
End Sub

Private Sub StopPlaybackBass()
    Bass.BASS_Stop()
    Bass.BASS_StreamFree(mMP3Stream)
    Bass.BASS_Free()
    mMP3Stream = 0
    mBassInitalized = False
End Sub

Private Sub AdjustPitch()
    If mMP3Stream <> 0 Then
      Bass.BASS_ChannelSetAttribute(mMP3Stream, _
                BASSAttribute.BASS_ATTRIB_TEMPO_PITCH, nudKey.Value)
    End If
End Sub

Private Sub AdjustVolume()
    If mMP3Stream <> 0 Then
      Bass.BASS_ChannelSetAttribute(mMP3Stream, _
           BASSAttribute.BASS_ATTRIB_VOL, _
           If(trbVolume.Value = 0, 0, (trbVolume.Value / 100)))
    End If
End Sub

Points of Interest

I would like to thank:

  • Nikolay Nikolov for writing the original CDG code in C++
  • The authors of the BASS sound library
  • Anyone else whose code snippets I may have borrowed

History

  • 1.0 - Initial revision.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Ron Schuler
Software Developer
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberkylehllewell4-May-13 6:51 
QuestionBackground Image PinmemberMember 93246477-Aug-12 16:45 
AnswerRe: Background Image PinmemberMember 222695111-Nov-12 12:39 
QuestionProblem with WMP Pinmemberjeff parnau17-Jul-12 4:26 
QuestionWeb Version? Pinmemberpclady6-Mar-12 10:47 
QuestionExtract text from cdg? Pinmembercjtaylor23-Feb-12 7:49 
AnswerRe: Extract text from cdg? Pinmembermoralam4-Apr-12 18:35 
Could you share with me a copy of C# code?
AnswerRe: Extract text from cdg? PinmemberRon Schuler5-Apr-12 1:41 
QuestionUse an image for background? PinmemberMember 842142021-Nov-11 11:29 
AnswerRe: Use an image for background? PinmemberMember 842142023-Nov-11 2:21 
QuestionSharpZipLib not always able to unzip files Pinmemberbdk01729-Nov-11 12:21 
AnswerRe: SharpZipLib not always able to unzip files PinmemberRon Schuler9-Nov-11 15:25 
GeneralRe: SharpZipLib not always able to unzip files PinmemberMember 842142021-Nov-11 9:59 
QuestionKaraoke ActiveX Pinmemberjogofo24-Aug-11 7:57 
AnswerRe: Karaoke ActiveX PinmemberRon Schuler25-Aug-11 2:46 
GeneralRe: Karaoke ActiveX Pinmemberjogofo25-Aug-11 3:58 
Questionhow to create a .cdg file? PinmemberMember 96086022-Jun-11 0:32 
AnswerRe: how to create a .cdg file? PinmemberRon Schuler22-Jun-11 2:01 
GeneralRe: how to create a .cdg file? PinmemberMember 96086027-Jun-11 0:34 
Generaltext render Pinmembertrigstig2-Jun-11 8:43 
GeneralRe: text render PinmemberRon Schuler2-Jun-11 16:30 
GeneralError initializing Audio System Pinmemberbillymac105923-Oct-10 14:11 
GeneralAwesome implementation! Pinmemberdsm20008-Aug-10 6:50 
GeneralRe: Awesome implementation! PinmemberRon Schuler8-Aug-10 9:34 
GeneralVariable on the fly CDG timing Pinmemberdsm20009-Aug-10 17:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 25 Jun 2010
Article Copyright 2010 by Ron Schuler
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid