Click here to Skip to main content
11,925,292 members (59,473 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


17 bookmarked

MP3 + CDG Karaoke Player

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


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.


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()
      If mMP3Stream <> 0 AndAlso Bass.BASS_ChannelIsActive(mMP3Stream) = _
                    BASSActive.BASS_ACTIVE_PLAYING Then
      End If
      If mCDGFileName = "" Or mMP3FileName = "" Then
        MsgBox("Cannot find a CDG and MP3 file to play together.")
        Exit Sub
      End If
      mPaused = False
      mStop = False
      mFrameCount = 0
      mCDGFile = New CDGFile(mCDGFileName)
      Dim cdgLength As Long = mCDGFile.getTotalDuration
      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)
        End While
        mFrameCount += 1
        mCDGWindow.PictureBox1.Image = mCDGFile.RGBImage
        mCDGWindow.PictureBox1.BackColor = CType(mCDGFile.RGBImage, Bitmap).GetPixel(1, 1)
        Dim myFrameRate As Single = Math.Round(mFrameCount / (pos / 1000), 1)
      End While
    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
      Dim temp As New MemoryStream
        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)
      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))
    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 _
      mMP3Stream = AddOn.Fx.BassFx.BASS_FX_TempoCreate(mMP3Stream, _
                   Or BASSFlag.BASS_SAMPLE_LOOP)
      If mMP3Stream <> 0 Then
        Bass.BASS_ChannelPlay(mMP3Stream, False)
        Throw New Exception(String.Format("Stream error: {0}", _
      End If
    End If
End Sub

Private Sub StopPlaybackBass()
    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


  • 1.0 - Initial revision.


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

You may also be interested in...

Comments and Discussions

QuestionPicture Background Pin
Member 1159260611-Apr-15 14:56
memberMember 1159260611-Apr-15 14:56 
GeneralMy vote of 5 Pin
kylehllewell4-May-13 7:51
memberkylehllewell4-May-13 7:51 
QuestionBackground Image Pin
Member 93246477-Aug-12 17:45
memberMember 93246477-Aug-12 17:45 
AnswerRe: Background Image Pin
Member 222695111-Nov-12 13:39
memberMember 222695111-Nov-12 13:39 
QuestionProblem with WMP Pin
jeff parnau17-Jul-12 5:26
memberjeff parnau17-Jul-12 5:26 
QuestionWeb Version? Pin
pclady6-Mar-12 11:47
memberpclady6-Mar-12 11:47 
QuestionExtract text from cdg? Pin
cjtaylor23-Feb-12 8:49
membercjtaylor23-Feb-12 8:49 
AnswerRe: Extract text from cdg? Pin
moralam4-Apr-12 19:35
membermoralam4-Apr-12 19:35 
AnswerRe: Extract text from cdg? Pin
Ron Schuler5-Apr-12 2:41
memberRon Schuler5-Apr-12 2:41 
QuestionUse an image for background? Pin
Member 842142021-Nov-11 12:29
memberMember 842142021-Nov-11 12:29 
AnswerRe: Use an image for background? Pin
Member 842142023-Nov-11 3:21
memberMember 842142023-Nov-11 3:21 
QuestionSharpZipLib not always able to unzip files Pin
bdk01729-Nov-11 13:21
memberbdk01729-Nov-11 13:21 
AnswerRe: SharpZipLib not always able to unzip files Pin
Ron Schuler9-Nov-11 16:25
memberRon Schuler9-Nov-11 16:25 
GeneralRe: SharpZipLib not always able to unzip files Pin
Member 842142021-Nov-11 10:59
memberMember 842142021-Nov-11 10:59 
QuestionKaraoke ActiveX Pin
jogofo24-Aug-11 8:57
memberjogofo24-Aug-11 8:57 
AnswerRe: Karaoke ActiveX Pin
Ron Schuler25-Aug-11 3:46
memberRon Schuler25-Aug-11 3:46 
GeneralRe: Karaoke ActiveX Pin
jogofo25-Aug-11 4:58
memberjogofo25-Aug-11 4:58 
Questionhow to create a .cdg file? Pin
Member 96086022-Jun-11 1:32
memberMember 96086022-Jun-11 1:32 
AnswerRe: how to create a .cdg file? Pin
Ron Schuler22-Jun-11 3:01
memberRon Schuler22-Jun-11 3:01 
GeneralRe: how to create a .cdg file? Pin
Member 96086027-Jun-11 1:34
memberMember 96086027-Jun-11 1:34 
Generaltext render Pin
trigstig2-Jun-11 9:43
membertrigstig2-Jun-11 9:43 
GeneralRe: text render Pin
Ron Schuler2-Jun-11 17:30
memberRon Schuler2-Jun-11 17:30 
GeneralError initializing Audio System Pin
billymac105923-Oct-10 15:11
memberbillymac105923-Oct-10 15:11 
GeneralAwesome implementation! Pin
dsm20008-Aug-10 7:50
memberdsm20008-Aug-10 7:50 
GeneralRe: Awesome implementation! Pin
Ron Schuler8-Aug-10 10:34
memberRon Schuler8-Aug-10 10:34 
GeneralVariable on the fly CDG timing Pin
dsm20009-Aug-10 18:53
memberdsm20009-Aug-10 18:53 
GeneralRe: Variable on the fly CDG timing Pin
Ron Schuler10-Aug-10 3:29
memberRon Schuler10-Aug-10 3:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 25 Jun 2010
Article Copyright 2010 by Ron Schuler
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid