Click here to Skip to main content
15,891,423 members
Articles / Multimedia / DirectX

Play and Visualize WAV Files using Managed Direct Sound with VB.NET

Rate me:
Please Sign up or sign in to vote.
4.78/5 (32 votes)
21 Dec 2007CPOL11 min read 404.7K   87   149
“Circular Buffers” is an application developed in VB.NET (VS 2003).

Introduction

As a VB.NET developer, I must admit that it is difficult getting decent code for DirectSound on the internet. Most of the examples are either in cryptic C/C++ or in C# (a close relation to VB.NET). The benefit of the latter is that it uses the familiar .NET Framework.

This tutorial takes you through the process of creating a simple utility application which will display and play a WAV file or portions of it as selected from a simple user interface.

For the non-initiated in the work of managed direct sound, I will take you through a brief introduction of DirectSound and jump into the topic of circular buffers in direct sound. For the already initiated, I will delve into the WAV file structure culminating with a class to parse a WAV file. To get the application working, the use of system timers will follow. Last but not least is putting all the code together.

An assumption made is that you are already familiar with DirectX and you have installed the DirectX SDK on your development platform.

About the Application

Image 1

“Circular Buffers” is an application developed in VB.NET (VS 2003). It demonstrates the following concepts:

  1. Playing a WAV file using a DirectSound static buffer
  2. Reading a WAV file and parsing it in preparation of playing
  3. Playing a WAV file stream using a DirectSound circular buffer
  4. Using the system timer to have precise control on timed events
  5. Visualizing WAV file data as a graph of sound values and Graphic double buffering
  6. Playing a WAV file data array using a DirectSound circular buffer
  7. Selecting portions of a WAV file and playing it using a static buffer
  8. Simple mixing of two sounds

Getting Started with DirectSound

DirectSound is part of the DirectX components and specifically handles playback of sound, including mono, stereo, 3-D sound and multi-channel sound. To begin, load the DirectSound reference into your VB.NET project as shown.

Image 2

By adding a reference to DirectSound, you expose four basic objects required in this project to play and manipulate sounds:

ObjectPurpose
Microsoft.DirectX.DirectSound.Device This is the main audio device object required to use DirectSound.
Microsoft.DirectX.DirectSound.WaveFormat Holds the required header properties of a WAV. For custom sounds, you must set all the parameters.
Microsoft.DirectX.DirectSound.SecondaryBuffer

 

This is the buffer to which we write our sound data before the primary hardware mixes and plays the sound. You can have as many secondary buffers as RAM can allow but only 1 primary buffer which is found in the hardware.
Microsoft.DirectX.DirectSound.BufferDescription Defines the capabilities of the audio device given the WAV format. 3-D sounds, volume control, frequency, panning can be set.

Minimum Required Code to Use DirectSound

VB.NET
'Play a sound wave using a default static buffer
 Private Sub cmdDefault_Click(……) Handles cmdDefault.Click
   Try
      SoundDevice = New Microsoft.DirectX.DirectSound.Device
   SoundDevice.SetCooperativeLevel(Me.Handle_
   , Microsoft.DirectX.DirectSound.CooperativeLevel.Normal)
    SbufferOriginal = New _ Microsoft.DirectX.DirectSound._
    SecondaryBuffer(SoundFile, SoundDevice)
     SbufferOriginal.Play(0,_
        Microsoft.DirectX.DirectSound.BufferPlayFlags.Looping)
   Catch ex As Exception
   End Try
 End Sub

The code shown above is the minimum code required to play a sound from a WAV file. The steps required are:

  1. Create a new sound device and assign a valid window handle as one parameter and set the cooperative level.
    • Priority: When the application has focus, only its sound will be audible
    • Normal: Restricts all sound output to 8-bit
    • WritePrimary: Allows the application to write to the primary buffer
  2. Create a secondary sound buffer and assign a valid filename/file stream and audio device as the input.
    • The sound file can only be a valid WAV file.
  3. Call the play method of the secondary buffer

Playing a WAV File using a DirectSound Static Buffer

A static buffer is by the name static. The content does not change in time and is loaded once. For continuous sound play, the secondary buffer play method uses the looping option. The steps outlined above use a static buffer. The contents of the WAV file are loaded into the secondary buffer and played.

A static buffer is best used when you have small WAV files whose size will not consume much resource. The procedure cmdDefault_Click in the above code creates and plays a static buffer.

Reading a WAV File and Parsing it in Preparation of Playing

The WAV file format is a subset of Microsoft's RIFF specification for the storage of multimedia files. A RIFF file starts out with a file header followed by a sequence of data chunks. A WAVE file is often just a RIFF file with a single "WAVE" chunk which consists of two sub-chunks -- a "fmt" chunk specifying the data format and a "data" chunk containing the actual sample data.

The figure below depicts the WAV file structure. The class CWAVReader parses the WAV file structure extracting the header details (WAV format) and actual sound data.

Image 3

The code below depicts the constructor with a series of methods parsing the WAV file structure.

VB.NET
‘Constructor to open stream
   Sub New(ByVal SoundFilePathName As String)
       mWAVFileName = SoundFilePathName
       mOpen = OpenWAVStream(mWAVFileName)
       '******************* MAIN WORK HERE ******************
       'Parse the WAV file and read the
       If mOpen Then
              'Read the Header Data in THIS ORDER
              'Each Read results in the File Pointer Moving
              mChunkID = ReadChunkID(mWAVStream)
              mChunkSize = ReadChunkSize(mWAVStream)
              mFormatID = ReadFormatID(mWAVStream)
              mSubChunkID = ReadSubChunkID(mWAVStream)
              mSubChunkSize = ReadSubChunkSize(mWAVStream)
              mAudioFormat = ReadAudioFormat(mWAVStream)
              mNumChannels = ReadNumChannels(mWAVStream)
              mSampleRate = ReadSampleRate(mWAVStream)
              mByteRate = ReadByteRate(mWAVStream)
              mBlockAlign = ReadBlockAlign(mWAVStream)
              mBitsPerSample = ReadBitsPerSample(mWAVStream)
              mSubChunkIDTwo = ReadSubChunkIDTwo(mWAVStream)
              mSubChunkSizeTwo = ReadSubChunkSizeTwo(mWAVStream)
              mWaveSoundData = ReadWAVSampleData(mWAVStream)
              mWAVStream.Close()
       End If
   End Sub

NOTE: THE ORDER MUST BE MAINTAINED! THE CODE USES A BINARY STREAM READ WHICH ADVANCES THE FILE POINTER.

Parsing the binary stream is not difficult. This involves reading a number of bytes as required using the binary reader ReadBytes method.

The code below reads the chunk ID from a WAV file. Notice that the chunk ID is in BIG-ENDIAN.

Computer architectures differ in terms of byte ordering. In some, data is stored left to right, which is referred to as big-endian. In others data is stored from right to left, which is referred to as little-endian. A notable computer architecture that uses big-endian byte ordering is Sun's Sparc. Intel architecture uses little-endian byte ordering, as does the Compaq Alpha processor.

VB.NET
'Read the ChunkID and return a string
Private Function ReadChunkID(….) As String
   Dim DataBuffer() As Byte
   Dim DataEncoder As System.Text.ASCIIEncoding
   Dim TempString As Char()
      DataEncoder = New System.Text.ASCIIEncoding
   DataBuffer = WAVIOstreamReader.ReadBytes(4)
   'Ensure we have data to spit out
   If DataBuffer.Length <> 0 Then
      TempString = DataEncoder.GetChars(DataBuffer, 0, 4)
      Return TempString(0) & TempString(1) & TempString(2) & TempString(3)
   Else
      Return ""
   End If
End Function

Since we are reading the data and converting the same into text based on the relative location (the array is read from location 0 to location 3), this is a big-endian value.

Small-endian values require a much more complicated function. The binary stream is read but the values are reversed and padded to ensure correct alignment, then converted to either text or value. The code below is one such function which takes up a byte array and reverses it to return the small-endian value.

VB.NET
'Get the small endian value
  Private Function GetLittleEndianStringValue(..) As String
    Dim ValueString As String = "&h"
    If DataBuffer.Length <> 0 Then
       'In little endian, we reverse the array data
       and pad the same where the length is 1
       If Hex(DataBuffer(3)).Length = 1 Then
            ValueString &= "0" & Hex(DataBuffer(3))
       Else
            ValueString &= Hex(DataBuffer(3))
       End If
       If Hex(DataBuffer(2)).Length = 1 Then
            ValueString &= "0" & Hex(DataBuffer(2))
       Else
            ValueString &= Hex(DataBuffer(2))
       End If
       If Hex(DataBuffer(1)).Length = 1 Then
            ValueString &= "0" & Hex(DataBuffer(1))
       Else
            ValueString &= Hex(DataBuffer(1))
       End If
       If Hex(DataBuffer(0)).Length = 1 Then
            ValueString &= "0" & Hex(DataBuffer(0))
       Else
            ValueString &= Hex(DataBuffer(0))
       End If
    Else
       ValueString = "0"
    End If
    GetLittleEndianStringValue = ValueString
  End Function

After reading the WAV’s properties, the final function is to read the entire sound data. The sound is read as a series of int16 data blocks. The memory stream has a method named ReadInt16, which is called repeatedly. The code below reads the actual sound values and converts the data from unsigned data to signed int16.

VB.NET
'returns the wave data as a byte array
   Public Function GetSoundDataValue() As Int16()
      Dim DataCount As Integer
      Dim tempStream As IO.BinaryReader
      tempStream = New IO.BinaryReader(New IO.MemoryStream(mWaveSoundData))
      tempStream.BaseStream.Position = 0
      'Create a data array to hold the data read from the stream
      'Read chunks of int16 from the stream (already aligned!)
      Dim tempData(CInt(tempStream.BaseStream.Length / 2)) As Int16
      While DataCount <= tempData.Length - 2
        tempData(DataCount) = tempStream.ReadInt16()
        DataCount += 1
      End While
      tempStream.Close()
      tempStream = Nothing
      Return tempData
   End Function

Using the System Timer to have Precise Control on Timed Events

The system.timers.timer works in much the same way as does the Windows Forms timer, but does not require the Windows message pump. Other than that, the primary difference between server timers and Windows Forms timers is that the event handlers for server timers execute on thread pool threads. This makes it possible to maintain a responsive user interface even if the event handler takes a long time to execute. Another critical difference in this case of audio programming is higher precision and thread safety.

The class timer’s constructor takes in a time interval and a function to call after the elapse of the interval. The system.timers.timer object is set to autoreset and thus continuously calls the function after the interval. The use of delegates (pointer to a function/sub) is used. Thus the timer object gets the timer interval and a delegate (pointer) of type System.Timers.ElapsedEventHandler to call. This class is used to monitor the sound buffer and ‘top-up’ data to play and also to paint the progress of the play bar while playing music.

Playing a WAV File Stream using a DirectSound Circular Buffer

According to Wikipedia, “A circular buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure lends itself easily to buffering data streams.” Pictorially, a circular buffer is as shown in the figure below:

Image 4

The write pointer identifies a location from which we can write sound data. The play pointer identifies the location where the sound buffer will play data from. The red boxes identify a location where data can be written to.

In the first scenario, the write pointer is positioned at a location point larger than the play pointer. As the play pointer advances, the write pointer needs to advance with latency not large enough to get a distortion. In the second scenario, the write pointer has wrapped around and is now at a location smaller than the play pointer.

When the write pointer gets to location 7, it has to warp around. The following code enables wrapping around of the write pointer and returns the amount of data already played which is the location to which new data has to be written to.

VB.NET
'get the played data size
Function GetPlayedSize() As Integer
    Dim Pos As Integer
    Pos = SbufferOriginal.PlayPosition
    If Pos < NextWritePos Then
       Return Pos + (SbufferOriginal.Caps.BufferBytes - NextWritePos)
    Else
       Return Pos - NextWritePos
    End If
End Function

The PlayPosition is a property of the secondary sound buffer and returns the position of the play pointer. NextWritePos is an internal pointer used to identify the location of where to write data to.

As the play pointer advances, we must continuously add data to the circular buffer. In this case, we shall use a memory stream from which to read data from and write to the circular stream. As mentioned before, a circular buffer is very useful if there is a large WAV file to be read and you intend to play the data in small chunks as opposed to reading the entire data to memory. There are two ways of ‘filling’ up the circular stream: use of notifications or use of polling technique. I have implemented the latter. A system timer is used to continuously ‘fill’ the circular stream with data.

At intervals of 75 milliseconds, the timer object calls the function PlayEventHandler. This function calls other functions that determine the amount of data to write and thereafter writes this data from the stream into the secondary sound buffer.

VB.NET
'Update the Circular buffer based on either a stream of data array
Sub PlayerEventHandler(…)
   'Stop if we have read all data
   If PlayerPosition >= MYwave.SubChunkSizeTwo Then
     StopPlay()
   End If
   'If an array, use the dataArray to top up new data to the circular buffer
   If IsArray = False Then
     'Get the amount of data to write and thereafter write the data
     WriteData(GetPlayedSize())
   Else
     WriteDataArray(GetPlayedSize())
   End If
End Sub

The function GetPlayedSize uses the concept of circular buffers to return the amount of data to safely write on the secondary sound buffer. The WriteData function thereafter writes the data to the secondary buffer. The code below demonstrates the functionality required to top up the secondary buffer (circular buffer).

VB.NET
'Write data to the circular buffer (secondary buffer that is)
Sub WriteData(ByVal DataSize As Integer)
   Dim Tocopy As Integer
   'make sure the data is less than the latency amount of 300ms
   Tocopy = Math.Min(DataSize, TimeToDataSize(Latency))
   'Only write data if there is something to write!
   If Tocopy > 0 Then
      'Restore the buffer
      If SbufferOriginal.Status.BufferLost Then
      SbufferOriginal.Restore()
      End If
      'Copy the data to the buffer
      'The DataMemStream is a binary stream object.
      'This can also be a large WAV file still on harddisk
      SbufferOriginal.Write(NextWritePos, DataMemStream, Tocopy, _
            Microsoft.DirectX.DirectSound.LockFlag.None)
      'As data is read form the DataMemStream, the position
      '(internal of the structure) advances
      'by the size of Tcopy

      'Advance the total cumulative bytes read
      PlayerPosition += Tocopy
      'advance the NextWrite pointer
      NextWritePos += Tocopy
      'If we are at the end, we wrap round
      If NextWritePos >= SbufferOriginal.Caps.BufferBytes Then
      NextWritePos = NextWritePos - SbufferOriginal.Caps.BufferBytes
      End If
   End If
End Sub

The system.timers.timer object is also used to update the screen with the location of the player pointer with respect to the data being played and not the secondary buffer. The function MyPainPoint is called at the same time interval of 75 milliseconds. But I use a different timer to reduce the latency and sound distortion.

VB.NET
'The handler to the timer tick event :
'Paints the location of the player pointer on the sound graph as the data is played
Sub MyPainPoint(ByVal obj As Object, ByVal Args As System.Timers.ElapsedEventArgs)
   'Control to ensure we stop when the total cumulated bytes read is equal to
   'the total data size
   If PlayerPosition >= MYwave.SubChunkSizeTwo Then
     StopPlay()
     'Update the labels
     lblPos.Text = MYwave.SubChunkSizeTwo.ToString
     lbltime.Text = MYwave.PlayTimeSeconds().ToString
   End If
   'Draw a line red from top to bottom showing the current position based on play position
   'The PlayerPOsition is the absolute location of the current played data
   'This is taken as a ratio of the total data size and scaled to the width of the picture
   'control
   Dim XPos As Single = CSng((PlayerPosition / MYwave.SubChunkSizeTwo) * picWave.Width)
   Dim posgraphic As Graphics

   'Clone the original canvas (this has the original sound graph). We do not need to
   're-draw this large graph as it willtake much processing time!
   PlayPicture = CType(myPicture.Clone, Bitmap)
   posgraphic = Graphics.FromImage(PlayPicture)

   'Draw the pointer
   Dim Mypen As Pen = New Pen(Color.Red)
   posgraphic.DrawLine(Mypen, XPos, 0, XPos, picWave.Height)

   'Draw line to myPicture
   MyTime += TimerStep
   posgraphic.DrawImage(PlayPicture, picWave.Width, picWave.Height)

   'Update the status on the labels
   lblPos.Text = PlayerPosition.ToString
   lbltime.Text = (MyTime / 1000).ToString

   'force a redraw of the picture updated.
   Me.Invalidate(New Drawing.Rectangle(picWave.Left, picWave.Top, picWave.Width, _
        picWave.Height))
      End Sub

The initial drawing of the sound data graph is stored as a bitmap. This bitmap is continuously cloned and a red line is drawn onto the cloned bitmap at different locations to give an effect of movement.

Visualizing WAV File Data as a Graph of Sound Values

The function DrawGraph takes in an array of int16 data and plots it out on the (vertical mid-point) picture control. Double buffering is used to speed up the drawing process. A bitmap is first created, thereafter the graphics are drawn. Once the entire line graph is drawn, the graphic is then drawn onto the bitmap. The bitmap is then transferred to the picture control. This process if faster than drawing directly onto the picture control.

VB.NET
'Draws the Sound data as a wave onto a canvas using double buffering to speed up work
Function DrawGraph(ByVal Data() As Int16) As Bitmap
   'Create the Canvas
   Dim myBitmap As System.Drawing.Bitmap

   'Create an array to hold the wav data which we can sort
   Dim tempData(Data.Length) As Integer

   'Copy the data to the temporary location  ... can be done better
   Data.CopyTo(tempData, 0)

   'Sort the array to get the maximum and minimum Y values
   Array.Sort(tempData)

   'generate the Canvas (drawing board in memory
   myBitmap = New Bitmap(picWave.Width, picWave.Height)

   'Create your paint brush, pens and drawing objects
   Dim myGraphic As System.Drawing.Graphics
   myGraphic = Graphics.FromImage(myBitmap)

   'draw the background with a custom color
   myGraphic.Clear(Color.FromArgb(181, 223, 225))

   'Get the parameters to draw the data and scale to fit the canvas but
   'draw from the middle
   Dim YMax As Integer = tempData(Data.Length - 1)
   Dim YMin As Integer = tempData(0)
   Dim XMax As Integer = picWave.Width
   Dim Xmin As Integer = 0

   'Create an array of points to draw a line
   Dim PicPoint(Data.Length - 1) As System.Drawing.PointF
   Dim Count As Integer
   Dim Step1 As Single          'Scale the data between Ymax and Ymin
   Dim Step2 As Single          'Scale the data further to fit between the canvas height
   Dim step3 As Single          'Draw the point form the middle of the canvas

   Dim Mypen As New Pen(Color.FromArgb(24, 101, 123))

   'Draw the lines from the series of points representing the sound wav
   For Count = 0 To Data.Length - 1
     Step1 = CSng(Data(Count) / (YMax - YMin))
     Step2 = CSng(Step1 * picWave.Height / 2)
     step3 = CSng(Step2 + (picWave.Height / 2))
     PicPoint(Count) = New System.Drawing.PointF(CSng(XMax * _
        (Count / Data.Length)), step3)
   Next

   'Draw the lines
   myGraphic.DrawLines(Mypen, PicPoint)

   'Draw graphics onto canvas
   myGraphic.DrawImage(myBitmap, picWave.Width, picWave.Height)

   'return the picture memory object
   Return (myBitmap)
End Function

Playing a WAV File Data Array using a Direct Sound Circular Buffer

Playing data from an array is not very different from playing data from a memory stream. The only difference here is that the secondary buffer method has an overload to read data from an array. As the programmer, you have to fetch data from the source (a memory stream) and create the data array. As listed in the code, the memory stream is repositioned to the last location of a read (playerposition) and data is read from there to the length of safe data to write.

VB.NET
'Write data to a Data Array.... similar to the above. using memory a stream
Sub WriteDataArray(ByVal DataSize As Integer)
   Dim Tocopy As Integer
   'ensure we do not have a big latency . the maximum is 300 ms
   Tocopy = Math.Min(DataSize, TimeToDataSize(Latency))

   'is we have data, then write to the array and play
   If Tocopy > 0 Then
     'Restore the buffer
     If SbufferOriginal.Status.BufferLost Then
       SbufferOriginal.Restore()
     End If

     'Copy the data to the Array
     're-create the data array (this is very slow!!)
     ReDim DataArray(Tocopy - 1)

     'Position the memory stream to the last location we read from.
     DataMemStream.Position = PlayerPosition

     'Copy the data from the stream to the array
     DataMemStream.Read(DataArray, 0, Tocopy - 1)

     'Write the data to the secondary buffer
     SbufferOriginal.Write(NextWritePos, DataArray, _
        Microsoft.DirectX.DirectSound.LockFlag.None)

     'Advance the pointers
     PlayerPosition += Tocopy
     NextWritePos += Tocopy
     If NextWritePos >= SbufferOriginal.Caps.BufferBytes Then
       NextWritePos = NextWritePos - SbufferOriginal.Caps.BufferBytes
     End If
   End If
End Sub

Selecting Portions of a WAV File and Playing it using a Static Buffer

To play a selected portion of the sound file, highlight the portion and select capture 1 or capture 2 . If both buttons are selected on different portions, then two different sounds can be played simultaneously (mixing).

Image 5

To select a portion of the sound, toggle the left mouse button over the picture control and move the mouse to the right. Once you let go of the left mouse button, the portion to be played will be highlighted. Click on the capture 1 button. Repeat the same for another portion and click capture 2.

The selection is made possible by using the mousedown, mousemove and mouseup event of the picture control. The rectangle is made transparent by using alpha blending. The code listed below is the implementation:

VB.NET
'Draw the band over the selection
Sub DrawSelection()
    'Draw a rubber band
    Dim posgraphic As Graphics
    Dim RubberRect As Rectangle
    RubberRect = New Rectangle(StartPoint.X, 0, _
        EndPoint.X - StartPoint.X, picWave.Height - 3)

    'Clone the original canvas
    PlayPicture = CType(myPicture.Clone, Bitmap)
    posgraphic = Graphics.FromImage(PlayPicture)

    'Draw the pointer
    Dim Mypen As Pen = New Pen(Color.Green)

    'Create a transparent brush using alpha blending techniques
    Dim MyBrush As SolidBrush = New SolidBrush(Color.FromArgb(85, 204, 32, 92))

    'Draw the boarder
    posgraphic.DrawRectangle(Mypen, RubberRect)

    'Fill the color
    posgraphic.FillRectangle(MyBrush, RubberRect)
    'Draw the picture on the form with the updated section of music to clip
    posgraphic.DrawImage(PlayPicture, picWave.Width, picWave.Height)

    'redraw the portion only
    Me.Invalidate(New Drawing.Rectangle(picWave.Left, picWave.Top, _
        picWave.Width, picWave.Height))
End Sub

To play the custom select sound, data is read to a data array. You must ensure that the data read is aligned based on the blockalign value. If not, noise results which is not very pleasant to hear!

VB.NET
'Plays a segment of data based on the rubber-band we have drawn prior to
'raising this event
Public Sub SetSegment(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles cmdSeg1.Click, cmdSeg2.Click
   'set local variables to use
   Dim tag As Int16
   Dim theButton As Button
   Dim DataStart As Integer
   Dim DataStop As Integer
   Dim BufferSize As Integer
   'initialize the direct sound objects
   Dim Format As Microsoft.DirectX.DirectSound.WaveFormat
   Dim Desc As Microsoft.DirectX.DirectSound.BufferDescription
   Dim MixBuffer As Microsoft.DirectX.DirectSound.SecondaryBuffer

   cmdBrowse.Enabled = False
   cmdDefault.Enabled = False
   cmdCustom.Enabled = False
   cmdCircular.Enabled = False
   cmdSeg1.Enabled = False
   cmdSeg2.Enabled = True
   cmdStop.Enabled = False

   theButton = CType(sender, Button)
   theButton.Enabled = False

   'get the locations from where to read data from
   DataStart = CInt(MYwave.SubChunkSizeTwo * (StartPoint.X / picWave.Width))
   DataStop = CInt(MYwave.SubChunkSizeTwo * (EndPoint.X / picWave.Width))

   StartPoint = Nothing
   EndPoint = Nothing

   'ensure that the data is aligned.. if not, noise results
   DataStart = DataStart - (DataStart Mod CInt(MYwave.BlockAlign))
   DataStop = DataStop - (DataStop Mod CInt(MYwave.BlockAlign))

   'Get the data into a Data array
   Dim DataSegment(DataStop - DataStart) As Byte

   'Read the data from the Stream
   DataMemStream.Position = DataStart

   'Read from the stream to the array buffer
   DataMemStream.Read(DataSegment, 0, DataStop - DataStart)

   'Now play the sound.
   'For custom sound, you must set the format
   Format = New Microsoft.DirectX.DirectSound.WaveFormat
   Format.AverageBytesPerSecond = CInt(MYwave.ByteRate)
   Format.BitsPerSample = CShort(MYwave.BitsPerSample)
   Format.BlockAlign = CShort(MYwave.BlockAlign)
   Format.Channels = CShort(MYwave.NumChannels)
   Format.FormatTag = Microsoft.DirectX.DirectSound.WaveFormatTag.Pcm
   Format.SamplesPerSecond = CInt(MYwave.SampleRate)

   Desc = New Microsoft.DirectX.DirectSound.BufferDescription(Format)
   BufferSize = DataStop - DataStart + 1

   'ensure the size is also aligned
   BufferSize = BufferSize + (BufferSize Mod CInt(MYwave.BlockAlign))

   Desc.BufferBytes = BufferSize
   Desc.ControlFrequency = True
   Desc.ControlPan = True
   Desc.ControlVolume = True
   Desc.GlobalFocus = True

   'Play the sound
   Try
     MixBuffer = New Microsoft.DirectX.DirectSound.SecondaryBuffer(Desc, SoundDevice)
     MixBuffer.Stop()
     MixBuffer.SetCurrentPosition(0)

     If MixBuffer.Status.BufferLost Then
      MixBuffer.Restore()
     End If

     MixBuffer.Write(0, DataSegment, Microsoft.DirectX.DirectSound.LockFlag.None)
     MixBuffer.Play(0, Microsoft.DirectX.DirectSound.BufferPlayFlags.Looping)
   Catch ex As Exception
     MsgBox(ex.Message)
   End Try
End Sub

Points of Interest

Playing with DirectSound is fun, especially when you get some real sound after hours and days of struggling. It took me a couple of days to get the circular buffer working. The WAV parser was something that got me thinking especially the endian bit! I intend to build this further and incorporate FFT (fast fourier transform) for real music mixing!

So that is it! I hope this is helpful for you VB.NET direct sound enthusiasts who have not benefited from the C/C++, C# found on the internet. Much of the work done here was trial and error, again due to scanty material and books!

Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
ENO
Software Developer
Kenya Kenya
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalsource code Pin
PCarilli24-Aug-09 3:45
PCarilli24-Aug-09 3:45 
GeneralMy vote of 1 Pin
César de Souza2-Aug-09 12:58
professionalCésar de Souza2-Aug-09 12:58 
GeneralMore display ideas Pin
JonFrost17-Feb-09 1:09
JonFrost17-Feb-09 1:09 
Questionthis looks so promising... Pin
seanclancy15-Feb-09 0:50
seanclancy15-Feb-09 0:50 
AnswerRe: this looks so promising... Pin
JonFrost17-Feb-09 0:54
JonFrost17-Feb-09 0:54 
GeneralMulti channel waves Pin
JonFrost8-Feb-09 2:04
JonFrost8-Feb-09 2:04 
GeneralRe: Multi channel waves Pin
plouvou12-Feb-09 9:42
plouvou12-Feb-09 9:42 
GeneralRe: Multi channel waves Pin
JonFrost16-Feb-09 22:30
JonFrost16-Feb-09 22:30 
Here is the source as it is in my project atm. I'm not sure what state it's in but it ran the last time I tried it. I have added the multi-sample and multi-channel selection ability to it. I just need to add eventing for selection changes, that will return appropriate eventargs with a number of channels/samples selected and a nice easy way to straight access that data.

I have also thought about extrapolating this into a standardised multi-channel multi-sample editing control, for editing graphics as well, because they both work on the same concept (ie 32-ARGB has four physical channels, and the frames are the individual pixels, which makes 1 sample the value of red, green, blue or alpha for 1 frame).

Next though, I want to add grab handles to be able to move samples and the ability to re-sample streams 1 or more channels, essentially breaking the channel data into a collection of the base sample data (like recycle from propellerheads). This will also be a nice base for speech detection and recognition.

Anyway, let me prattle on no further. Have fun with it.

*/Form1.Designer.vb/*

<global.microsoft.visualbasic.compilerservices.designergenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form

'Form overrides dispose to clean up the component list.
<system.diagnostics.debuggernonusercode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<system.diagnostics.debuggerstepthrough()> _
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button
Me.PictureBox1 = New System.Windows.Forms.PictureBox
Me.HScrollBar1 = New System.Windows.Forms.HScrollBar
Me.NumericUpDown1 = New System.Windows.Forms.NumericUpDown
Me.StatusStrip1 = New System.Windows.Forms.StatusStrip
Me.ToolStripStatusLabel1 = New System.Windows.Forms.ToolStripStatusLabel
Me.ToolStripProgressBar1 = New System.Windows.Forms.ToolStripProgressBar
Me.Button2 = New System.Windows.Forms.Button
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.StatusStrip1.SuspendLayout()
Me.SuspendLayout()
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(12, 12)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(75, 23)
Me.Button1.TabIndex = 0
Me.Button1.Text = "&Open"
Me.Button1.UseVisualStyleBackColor = True
'
'PictureBox1
'
Me.PictureBox1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.PictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.PictureBox1.Location = New System.Drawing.Point(12, 41)
Me.PictureBox1.Name = "PictureBox1"
Me.PictureBox1.Size = New System.Drawing.Size(794, 362)
Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.PictureBox1.TabIndex = 1
Me.PictureBox1.TabStop = False
'
'HScrollBar1
'
Me.HScrollBar1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.HScrollBar1.Location = New System.Drawing.Point(12, 406)
Me.HScrollBar1.Name = "HScrollBar1"
Me.HScrollBar1.Size = New System.Drawing.Size(794, 19)
Me.HScrollBar1.TabIndex = 2
'
'NumericUpDown1
'
Me.NumericUpDown1.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.NumericUpDown1.DecimalPlaces = 2
Me.NumericUpDown1.Increment = New Decimal(New Integer() {1, 0, 0, 131072})
Me.NumericUpDown1.Location = New System.Drawing.Point(686, 12)
Me.NumericUpDown1.Maximum = New Decimal(New Integer() {25, 0, 0, 0})
Me.NumericUpDown1.Minimum = New Decimal(New Integer() {1, 0, 0, 131072})
Me.NumericUpDown1.Name = "NumericUpDown1"
Me.NumericUpDown1.Size = New System.Drawing.Size(120, 20)
Me.NumericUpDown1.TabIndex = 3
Me.NumericUpDown1.Value = New Decimal(New Integer() {1, 0, 0, 0})
'
'StatusStrip1
'
Me.StatusStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripStatusLabel1, Me.ToolStripProgressBar1})
Me.StatusStrip1.Location = New System.Drawing.Point(0, 425)
Me.StatusStrip1.Name = "StatusStrip1"
Me.StatusStrip1.Size = New System.Drawing.Size(818, 22)
Me.StatusStrip1.TabIndex = 4
Me.StatusStrip1.Text = "StatusStrip1"
'
'ToolStripStatusLabel1
'
Me.ToolStripStatusLabel1.Name = "ToolStripStatusLabel1"
Me.ToolStripStatusLabel1.Size = New System.Drawing.Size(111, 17)
Me.ToolStripStatusLabel1.Text = "ToolStripStatusLabel1"
'
'ToolStripProgressBar1
'
Me.ToolStripProgressBar1.Name = "ToolStripProgressBar1"
Me.ToolStripProgressBar1.Size = New System.Drawing.Size(100, 16)
'
'Button2
'
Me.Button2.Location = New System.Drawing.Point(93, 12)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(75, 23)
Me.Button2.TabIndex = 5
Me.Button2.Text = "&Match"
Me.Button2.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(818, 447)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.StatusStrip1)
Me.Controls.Add(Me.NumericUpDown1)
Me.Controls.Add(Me.HScrollBar1)
Me.Controls.Add(Me.PictureBox1)
Me.Controls.Add(Me.Button1)
Me.Name = "Form1"
Me.Text = "Form1"
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).EndInit()
Me.StatusStrip1.ResumeLayout(False)
Me.StatusStrip1.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()

End Sub
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox
Friend WithEvents HScrollBar1 As System.Windows.Forms.HScrollBar
Friend WithEvents NumericUpDown1 As System.Windows.Forms.NumericUpDown
Friend WithEvents StatusStrip1 As System.Windows.Forms.StatusStrip
Friend WithEvents ToolStripStatusLabel1 As System.Windows.Forms.ToolStripStatusLabel
Friend WithEvents ToolStripProgressBar1 As System.Windows.Forms.ToolStripProgressBar
Friend WithEvents Button2 As System.Windows.Forms.Button

End Class

*/Form1.vb/*

Imports System.IO
Imports System.Text

Public Class Form1

Dim m_Stream As Stream
Dim m_Reader As BinaryReader
Dim m_ChunkLen As Integer
Dim m_DataLen As Integer
Dim m_Data As Int16()

Dim m_Channels As Integer
Dim m_Align As Integer
Dim m_SampleChannelSize As Integer
Dim m_SampleRate As Integer

Dim m_Colors As Color() = New Color() {Color.Red, Color.Blue, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black}

Dim m_CMin() As Int32
Dim m_CMax() As Int32

Dim m_Display As DisplayData
Dim m_DisplayNew As DisplayData

'Stores the point data for the currently displayed section
Dim m_Point()() As PointF

Dim m_Bitmap As Bitmap

Dim m_Loaded As Boolean

Dim m_DragStartSample As Integer
Dim m_DragStartChannel As Integer
Dim m_SelectRect As RectangleF
Dim m_IsSelect As Boolean

Dim l_CurSampleChan As New Point

Dim m_Button As Boolean

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog

ofd.Filter = "WAV Files (*.wav)|*.wav|All Files (*.*)|*.*"

If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
'A file was selected, open it

m_Data = Nothing

If Not m_Stream Is Nothing Then
m_Reader.Close()
m_Reader = Nothing
m_Stream.Close()
m_Stream = Nothing
End If

m_Stream = ofd.OpenFile

OpenWav(m_Stream)

m_Loaded = True

m_Display = New DisplayData
m_DisplayNew = New DisplayData

InitDisplayData()

ReDim m_Point(m_Channels - 1)

SetGraph()
End If
End Sub

Private Sub OpenWav(ByVal wav As Stream)
m_Reader = New BinaryReader(wav)

Console.WriteLine("Chunk ID : " & ReadChunkID())
m_ChunkLen = ReadInt32()
Console.WriteLine("Chunk Size : " & m_ChunkLen)
Console.WriteLine("Chunk Format : " & ReadChunkID())
While m_Stream.Position < (m_ChunkLen - 8)
ReadSubChunk()
End While
End Sub

Private Sub InitDisplayData()
With m_DisplayNew
.DisplayArea = PictureBox1.ClientSize
.SamplesPerPixel = 1
.SampleCount = m_DataLen / ((m_SampleChannelSize / 8) * m_Channels)
.DisplayOffset = 0
End With
End Sub

Private Sub SetGraph()
If Not DisplayData.Equals(m_Display, m_DisplayNew) Then
m_Display.Update(m_DisplayNew)

HScrollBar1.Minimum = 0
HScrollBar1.Maximum = m_Display.SampleCount - m_Display.SamplesDisplayed

HScrollBar1.SmallChange = (m_Display.SampleCount - m_Display.SamplesDisplayed) / (1500 * m_Display.SamplesPerPixel)
HScrollBar1.LargeChange = (m_Display.SampleCount - m_Display.SamplesDisplayed) / (1000 * m_Display.SamplesPerPixel)

'ToolStripStatusLabel1.Text = GetHMS(m_DisplayOffset / m_SampleRate) & " - " & GetHMS((m_DisplayOffset + m_NumDisplaySamples) / m_SampleRate)
ToolStripStatusLabel1.Text = GetHMS(Math.Round(m_Display.DisplayOffset / m_SampleRate)) & " (" & m_Display.DisplayOffset & ") - " & GetHMS(Math.Round((m_Display.DisplayOffset + m_Display.SamplesDisplayed) / m_SampleRate)) & " (" & (m_Display.DisplayOffset + m_Display.SamplesDisplayed) & ")"

RefreshBuffers()
End If

PictureBox1.Image = DrawGraph()
End Sub

Private Function GetHMS(ByVal time As Double) As String
Return TimeSpan.FromSeconds(time).ToString
End Function

Private Sub ReadChunk()

End Sub

Private Sub ReadSubChunk()
Dim SCID As String
Dim CS As Integer

SCID = ReadChunkID()
Console.WriteLine("Sub-Chunk ID : " & SCID)
CS = ReadInt32()
Console.WriteLine("Sub-Chunk Size: " & CS)

Select Case SCID

Case "fmt "
Console.WriteLine("Format : " & ReadInt16())
m_Channels = ReadInt16()
Console.WriteLine("Channels : " & m_Channels)
m_SampleRate = ReadInt32()
Console.WriteLine("Sample Rate : " & m_SampleRate)
Console.WriteLine("Byte Rate : " & ReadInt32())
m_Align = ReadInt16()
Console.WriteLine("Block Align : " & m_Align)
m_SampleChannelSize = ReadInt16()
Console.WriteLine("Sample Size : " & m_SampleChannelSize)
m_Reader.ReadBytes(CS - 16)

Case "data"
m_DataLen = CS
m_Data = ReadSoundData()

Case Else
'skip
m_Reader.ReadBytes(CS)

End Select
End Sub

Private Function ReadChunkID() As String
Dim l_Bytes As Byte()

l_Bytes = m_Reader.ReadBytes(4)

If l_Bytes.Length > 0 Then
Return Encoding.ASCII.GetString(l_Bytes)
Else
Return ""
End If
End Function

Private Function ReadSubChunkID() As String
Dim l_Bytes As Byte()

l_Bytes = m_Reader.ReadBytes(4)

If l_Bytes.Length > 0 Then
Return Convert.ToString(l_Bytes(0), 16).PadLeft(2, "0") & Convert.ToString(l_Bytes(1), 16).PadLeft(2, "0") & Convert.ToString(l_Bytes(2), 16).PadLeft(2, "0") & Convert.ToString(l_Bytes(3), 16).PadLeft(2, "0")
Else
Return ""
End If
End Function

Private Function ReadInt32() As Int32
Dim l_Bytes As Byte()

l_Bytes = m_Reader.ReadBytes(4)

l_Bytes.Reverse()

If l_Bytes.Length > 0 Then
Return BitConverter.ToInt32(l_Bytes, 0)
Else
Return 0
End If
End Function

Private Function ReadInt16() As Int16
Dim l_Bytes As Byte()

l_Bytes = m_Reader.ReadBytes(2)

'l_Bytes.Reverse()

If l_Bytes.Length > 0 Then
Return BitConverter.ToInt16(l_Bytes, 0)
Else
Return 0
End If
End Function

Private Function ReadSoundData() As Int16()
Dim al As New ArrayList
Dim l_Length As Integer = m_DataLen / (m_SampleChannelSize / 8)
Dim data(l_Length - 1) As Int16
'ReDim ReadSoundData(l_Length - 1)

Dim l_Chan As Integer = 1
Dim l_Val As Int16

ReDim m_CMin(m_Channels - 1)
ReDim m_CMax(m_Channels - 1)

For c As Integer = 0 To m_Channels - 1
m_CMax(c) = Int16.MinValue
m_CMin(c) = Int16.MaxValue
Next

ToolStripProgressBar1.Minimum = 0
ToolStripProgressBar1.Maximum = l_Length / m_Channels
ToolStripProgressBar1.Value = 0

For i As Integer = 0 To (l_Length / m_Channels) - 1
For c = 0 To m_Channels - 1
l_Val = m_Reader.ReadInt16()

If l_Val > m_CMax(c) Then m_CMax(c) = l_Val
If l_Val < m_CMin(c) Then m_CMin(c) = l_Val

data((m_Channels * i) + c) = l_Val
Next

If i Mod 2500 = 0 Then
ToolStripProgressBar1.Value = i

Application.DoEvents()
End If
Next

For c As Integer = 0 To m_Channels - 1
Console.WriteLine("C" & c + 1 & "Min: " & m_CMin(c))
Console.WriteLine("C" & c + 1 & "Max: " & m_CMax(c))
Next

ReadSoundData = data
data = Nothing
End Function

Private Sub RefreshBuffers()
'This loop was changed to only process as many points as are displayable (ie. display are width)
For c As Integer = 0 To m_Channels - 1
m_Point(c) = Nothing
ReDim m_Point(c)(m_Display.SamplesDisplayed - 1)
Next

'For c As Integer = 0 To m_Channels - 1
' ReDim l_Point(c)((m_Data.Length / m_Channels) - 1)
'Next

Dim step1 As Single
Dim step2 As Single
Dim step3 As Single

Dim l_Index As Integer

Try
For i As Integer = 0 To m_Display.SamplesDisplayed - 1
For c As Integer = 0 To m_Channels - 1
l_Index = ((m_Channels * (m_Display.DisplayOffset + i)) + c)
'l_Index = ((m_DisplayOffset + (i * m_Channels)) + c)

'Console.WriteLine("Plot Data at " & c & "," & i & " (" & l_Index & ")")
step1 = CSng(m_Data(l_Index) / (m_CMax(c) - m_CMin(c)))
step2 = CSng(step1 * ((PictureBox1.Height / m_Channels) / 2))
step3 = CSng(step2 + ((c * (PictureBox1.Height / m_Channels)) + ((PictureBox1.Height / m_Channels) / 2)))
'l_Point(c)(i) = New PointF(CSng(l_MaxX * (i / ((m_Data.Length / m_Channels) / 2))), step3)
m_Point(c)(i) = New PointF(CSng(i / m_Display.SamplesPerPixel), step3)
Next
Next

Catch ex As Exception
Console.WriteLine("Error at index " & l_Index & " : " & ex.ToString)

End Try
End Sub

Private Function DrawGraph() As Bitmap
'Dim l_Temp(m_Data.Length - 1) As SByte

'm_Data.CopyTo(l_Temp, 0)

'Array.Sort(l_Temp)

'Dim l_MinY As Integer = l_Temp(0)
'Dim l_MaxY As Integer = l_Temp(m_Data.Length - 1)
'Dim l_MinX As Integer = 0
'Dim l_MaxX As Integer = PictureBox1.Width
'MaxX should always be the width of the display area
'Dim l_MaxX As Integer = Math.Min(PictureBox1.Width, (m_Data.Length / m_Channels) / 8)

'l_MaxX = 35000

m_Bitmap = New Bitmap(PictureBox1.Width, PictureBox1.Height)

Dim g As Graphics = Graphics.FromImage(m_Bitmap)

g.Clear(Color.FromArgb(181, 223, 225))

'This dim is fine

Dim l_Pen As Pen

For c As Integer = 0 To m_Channels - 1
l_Pen = New Pen(m_Colors(c))

g.DrawLines(l_Pen, m_Point(c))
Next

l_Pen = Nothing

If m_IsSelect Then
With m_SelectRect
.X = (Math.Min(m_DragStartSample, l_CurSampleChan.X) - m_Display.DisplayOffset) * (m_Display.DisplayArea.Width / m_Display.SamplesDisplayed)
.Y = Math.Min(m_DragStartChannel, l_CurSampleChan.Y) * (m_Display.DisplayArea.Height / m_Channels)
.Width = (Math.Abs(m_DragStartSample - l_CurSampleChan.X) + 1) * (m_Display.DisplayArea.Width / m_Display.SamplesDisplayed)
.Height = (Math.Abs(m_DragStartChannel - l_CurSampleChan.Y) + 1) * (m_Display.DisplayArea.Height / m_Channels)
End With

g.FillRectangle(New SolidBrush(Color.FromArgb(185, 0, 225, 0)), m_SelectRect)
'g.DrawRectangle(New Pen(Color.FromArgb(185, 0, 200, 0)), m_SelectRect)
End If

Return m_Bitmap
End Function

Private Sub HScrollBar1_Scroll(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles HScrollBar1.Scroll
If m_Loaded Then
m_DisplayNew.DisplayOffset = e.NewValue
SetGraph()
End If
End Sub

Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
If m_Loaded And Not Me.WindowState = FormWindowState.Minimized Then
m_DisplayNew.DisplayArea = PictureBox1.ClientSize
SetGraph()
End If

Application.DoEvents()
End Sub

Private Sub NumericUpDown1_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged
If m_Loaded Then
m_DisplayNew.SamplesPerPixel = NumericUpDown1.Value
SetGraph()
End If
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'Analyse the first 100 samples of channel 1 and determine the component frequencies (Sine-Waves)
For i As Integer = 0 To 99
Console.WriteLine("Sine : " & m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue)
Console.WriteLine("Angle (Rad): " & Math.Asin(m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue))
Console.WriteLine("Angle (Deg): " & Math.Asin(m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue) / (Math.PI / 180))
Console.WriteLine("2f : " & (Math.Asin(m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue) / (Math.PI / 180)) / Math.PI)
Console.WriteLine("f : " & ((Math.Asin(m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue) / (Math.PI / 180)) / Math.PI) / 2)
Console.WriteLine("Cosine : " & m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue)
Console.WriteLine("Angle (Rad): " & Math.Acos(m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue))
Console.WriteLine("Angle (Deg): " & Math.Acos(m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue) / (Math.PI / 180))
Console.WriteLine("2f : " & (Math.Acos(m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue) / (Math.PI / 180)) / Math.PI)
Console.WriteLine("f : " & ((Math.Acos(m_Data(GetDataIndex(i, 0)) / UInt16.MaxValue) / (Math.PI / 180)) / Math.PI) / 2)
Next
End Sub

Private Function GetDataIndex(ByVal sampleIndex As Integer, ByVal channelIndex As Integer)
Return (m_Channels * sampleIndex) + channelIndex
End Function

Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
'Enter selection mode
m_Button = True
'Drag Operation Start Sample Index
m_DragStartSample = m_Display.DisplayOffset + (e.X / m_Display.SamplesPerPixel)
m_DragStartSample = m_Display.DisplayOffset + (e.X - (e.X Mod (m_Display.DisplayArea.Width / m_Display.SamplesDisplayed))) / (m_Display.DisplayArea.Width / m_Display.SamplesDisplayed)
m_DragStartChannel = (e.Y - (e.Y Mod (m_Display.DisplayArea.Height / m_Channels))) / (m_Display.DisplayArea.Height / m_Channels)
Console.WriteLine("Sel drag start")
End Sub

Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If m_Button Then
Console.WriteLine("Sel drag move")

l_CurSampleChan.X = m_Display.DisplayOffset + (e.X / m_Display.SamplesPerPixel)
l_CurSampleChan.X = m_Display.DisplayOffset + (e.X - (e.X Mod (m_Display.DisplayArea.Width / m_Display.SamplesDisplayed))) / (m_Display.DisplayArea.Width / m_Display.SamplesDisplayed)
l_CurSampleChan.Y = (e.Y - (e.Y Mod (m_Display.DisplayArea.Height / m_Channels))) / (m_Display.DisplayArea.Height / m_Channels)

m_SelectRect = New RectangleF

'With m_SelectRect
' .X = Math.Min(e.X / m_Display.SamplesPerPixel, m_DragStartSample)
' .Y = Math.Min(m_DragStartChannel, (e.Y - (e.Y Mod (m_Display.DisplayArea.Height / m_Channels))) / (m_Display.DisplayArea.Height / m_Channels)) * (m_Display.DisplayArea.Height / m_Channels)
' .Width = Math.Abs((e.X / m_Display.SamplesPerPixel) - m_DragStartSample)
' .Height = (Math.Abs(m_DragStartChannel - ((e.Y - (e.Y Mod (m_Display.DisplayArea.Height / m_Channels))) / (m_Display.DisplayArea.Height / m_Channels))) + 1) * m_Display.DisplayArea.Height / m_Channels
'End With

'If e.X > m_DragStart Then
' 'Positive selection

Console.WriteLine(m_SelectRect)
Console.WriteLine(m_Display.DisplayOffset)

'ElseIf e.X < m_DragStart Then
' 'Negative selection
'End If
m_IsSelect = True

PictureBox1.Image = DrawGraph()
PictureBox1.Refresh()
End If
End Sub

Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
m_Button = False
Console.WriteLine("Sel drag end")
End Sub

Private Function GetSampleAtOffset(ByVal offset As Integer) As Integer

End Function

Private Function GetSampleAtPoint(ByVal p As Point) As Integer

End Function

Private Class DisplayData
Dim m_SamplesPerPixel As Single
Dim m_NumSamples As Integer
Dim m_NumDisplaySamples As Integer
Dim m_DisplayOffset As Integer
Dim m_DisplayArea As Size

Public Property DisplayArea() As Size
Get
Return m_DisplayArea
End Get
Set(ByVal value As Size)
m_DisplayArea = value
End Set
End Property

Public Property DisplayOffset() As Integer
Get
Return m_DisplayOffset
End Get
Set(ByVal value As Integer)
m_DisplayOffset = value
End Set
End Property

Public Property SampleCount() As Integer
Get
Return m_NumSamples
End Get
Set(ByVal value As Integer)
m_NumSamples = value
End Set
End Property

Public ReadOnly Property SamplesDisplayed() As Integer
Get
Return m_DisplayArea.Width * m_SamplesPerPixel
End Get
End Property

Public Property SamplesPerPixel() As Single
Get
Return m_SamplesPerPixel
End Get
Set(ByVal value As Single)
m_SamplesPerPixel = value
End Set
End Property

Public Overrides Function Equals(ByVal obj As Object) As Boolean
If obj.GetType.Equals(Me.GetType) Then
If Not obj Is Nothing Then
With CType(obj, DisplayData)
Return (.m_DisplayOffset = m_DisplayOffset) And (.m_DisplayArea = m_DisplayArea) And (.m_NumSamples = m_NumSamples) And (.m_SamplesPerPixel = m_SamplesPerPixel)
End With
Else
Return False
End If
Else
Return False
End If
End Function

Public Sub Update(ByVal disp As DisplayData)
m_DisplayArea = disp.m_DisplayArea
m_DisplayOffset = disp.m_DisplayOffset
m_NumSamples = disp.m_NumSamples
m_SamplesPerPixel = disp.m_SamplesPerPixel
End Sub
End Class

Private Class BufferedDisplayData
Dim m_SamplesPerPixel As BufferedValue(Of Single)
Dim m_NumSamples As BufferedValue(Of Integer)
Dim m_NumDisplaySamples As BufferedValue(Of Integer)
Dim m_DisplayOffset As BufferedValue(Of Integer)

Public Sub New()
m_SamplesPerPixel = New BufferedValue(Of Single)
m_NumSamples = New BufferedValue(Of Integer)
m_NumDisplaySamples = New BufferedValue(Of Integer)
m_DisplayOffset = New BufferedValue(Of Integer)
End Sub

Public Property DisplayOffset() As Integer
Get
Return m_DisplayOffset.Value
End Get
Set(ByVal value As Integer)
m_DisplayOffset.Value = value
End Set
End Property

Public Property SampleCount() As Integer
Get
Return m_NumSamples.Value
End Get
Set(ByVal value As Integer)
m_NumSamples.Value = value
End Set
End Property

Public Property SamplesDisplayed() As Integer
Get
Return m_NumDisplaySamples.Value
End Get
Set(ByVal value As Integer)
m_NumDisplaySamples.Value = value
End Set
End Property

Public Property SamplesPerPixel() As Single
Get
Return m_SamplesPerPixel.Value
End Get
Set(ByVal value As Single)
m_SamplesPerPixel.Value = value
End Set
End Property

Public ReadOnly Property IsChanged() As Boolean
Get
Return m_DisplayOffset.IsChanged Or m_NumSamples.IsChanged Or m_NumDisplaySamples.IsChanged Or m_SamplesPerPixel.IsChanged
End Get
End Property

Public Sub Reset()
m_DisplayOffset.Reset()
m_NumSamples.Reset()
m_NumDisplaySamples.Reset()
m_SamplesPerPixel.Reset()
End Sub

Public Sub Update()
m_DisplayOffset.Update()
m_NumSamples.Update()
m_NumDisplaySamples.Update()
m_SamplesPerPixel.Update()
End Sub
End Class

Private Class BufferedValue(Of T)
Dim m_Curr As T
Dim m_New As T
Dim m_Changed As Boolean

Public Sub New()
m_Curr = Nothing
m_New = Nothing
m_Changed = False
End Sub

Public Sub New(ByVal initialValue As T)
m_Curr = initialValue
m_New = initialValue
m_Changed = False
End Sub

Public Property Value() As T
Get
Return m_Curr
End Get
Set(ByVal value As T)
If Not Object.Equals(m_Curr, value) Then
m_New = value
m_Changed = True
End If
End Set
End Property

Public ReadOnly Property IsChanged() As Boolean
Get
Return m_Changed
End Get
End Property

Public Sub Reset()
m_New = m_Curr
m_Changed = False
End Sub

Public Sub Update()
m_Curr = m_New
m_Changed = False
End Sub
End Class
End Class

*/Form1.resx/*


<root>

<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace">
<xsd:element name="root" msdata:isdataset="true">
<xsd:complextype>
<xsd:choice maxoccurs="unbounded">
<xsd:element name="metadata">
<xsd:complextype>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minoccurs="0">

<xsd:attribute name="name" use="required" type="xsd:string">
<xsd:attribute name="type" type="xsd:string">
<xsd:attribute name="mimetype" type="xsd:string">
<xsd:attribute ref="xml:space">


<xsd:element name="assembly">
<xsd:complextype>
<xsd:attribute name="alias" type="xsd:string">
<xsd:attribute name="name" type="xsd:string">


<xsd:element name="data">
<xsd:complextype>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minoccurs="0" msdata:ordinal="1">
<xsd:element name="comment" type="xsd:string" minoccurs="0" msdata:ordinal="2">

<xsd:attribute name="name" type="xsd:string" use="required" msdata:ordinal="1">
<xsd:attribute name="type" type="xsd:string" msdata:ordinal="3">
<xsd:attribute name="mimetype" type="xsd:string" msdata:ordinal="4">
<xsd:attribute ref="xml:space">


<xsd:element name="resheader">
<xsd:complextype>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minoccurs="0" msdata:ordinal="1">

<xsd:attribute name="name" type="xsd:string" use="required">






<resheader name="resmimetype">
<value>text/microsoft-resx

<resheader name="version">
<value>2.0

<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

<metadata name="StatusStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17


GeneralRe: PART OF THE CODE IS RIGHT HERE ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ ABOVE THIS POST ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ Pin
tegezee15-Feb-10 9:27
tegezee15-Feb-10 9:27 
GeneralRe: Multi channel waves Pin
Member 816315416-Jan-12 14:50
Member 816315416-Jan-12 14:50 
GeneralSource Needed - Please Pin
bomedia7-Feb-09 13:33
bomedia7-Feb-09 13:33 
JokeRe: Source Needed - Please Pin
bomedia13-Feb-09 0:13
bomedia13-Feb-09 0:13 
GeneralRe: Source Needed - Please Pin
dangregory12-Mar-09 15:04
dangregory12-Mar-09 15:04 
GeneralGREAT ARTICLE BUT... Pin
Member 109444319-Dec-08 10:44
professionalMember 109444319-Dec-08 10:44 
GeneralSource code please Pin
Montxo18-Dec-08 11:13
Montxo18-Dec-08 11:13 
QuestionGreat code - but I got an error Pin
seanclancy21-Oct-08 6:52
seanclancy21-Oct-08 6:52 
QuestionNice but anybody has the source code yet ? Pin
plouvou17-Oct-08 9:32
plouvou17-Oct-08 9:32 
AnswerRe: Nice but anybody has the source code yet ? Pin
ENO21-Oct-08 4:22
ENO21-Oct-08 4:22 
QuestionI would love the source code [modified] Pin
seanclancy17-Oct-08 7:35
seanclancy17-Oct-08 7:35 
AnswerRe: I would love the source code Pin
ENO21-Oct-08 4:20
ENO21-Oct-08 4:20 
GeneralSpeed change Pin
seanclancy17-Oct-08 7:13
seanclancy17-Oct-08 7:13 
GeneralRe: Speed change Pin
plouvou17-Oct-08 9:38
plouvou17-Oct-08 9:38 
GeneralRe: Speed change Pin
plouvou12-Feb-09 9:47
plouvou12-Feb-09 9:47 
GeneralLoaderLock Pin
legcsabi8-Oct-08 6:40
legcsabi8-Oct-08 6:40 
GeneralRe: LoaderLock Pin
JonFrost26-Feb-09 0:43
JonFrost26-Feb-09 0:43 

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.