Click here to Skip to main content
15,890,336 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Capturing Audio and Replay It Using Direct Sound in VB

Rate me:
Please Sign up or sign in to vote.
4.57/5 (4 votes)
22 Sep 2016CPOL2 min read 20.4K   2   4
This tip describes how to capture audio and then replay it using Microsoft Direct Sound DLL.

Introduction

This tip describes how to capture audio and then replay it using Microsoft Direct Sound DLL. I have been searching about how to capture audio using direct Sound in VB over the internet for a couple of weeks, but I could not get any meaningful code. Finally, through try and error, I managed to get the code working. I then decided to write and share this article with everyone who is researching about sound capturing using Direct Sound. The code is very easy to understand. I will try to explain the whole thing, but I assume that you have an idea or have researched a bit about sound in waveformat and you have an idea on what audio is and how it is stored. What we are simply doing is capturing audio in wavformat using a capturebuffer, then write it to a secondary buffer. That audio which is stored in a secondary buffer is then replayed. Note that I used VB Studio 8 with this code.

Let's start. You need the following:

  1. Three buttons, named start, stop, play
  2. One Label
  3. Add reference to Microsoft Direct Sound DLL.
  4. Change configuration to x86 platform (In your VB Studio, go to Build>Configuration Manager)
  5. Remove loader lock (In your VB Studio, go to Debug>Exceptions>Managed Debugging Assistants>Uncheck Loader Lock)

Create a new VB application. Add your three buttons and a label which will be showing background activities happening upon clicking of your buttons. Double click on your form and import the following to your form. Paste the following code:

VB.NET
Imports Microsoft.DirectX.DirectSound
Imports System.IO
Imports System.Threading
Imports System.Windows.Forms
Imports System.Text
Imports System.Drawing
Imports System.Data
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Console
Imports System.Net.Sockets

Next. In the class of your form, declare the capture, create a capturebuffer used to capture sound, set a device to play your sound with, set a secondary buffer to store your sound, set bufferposition and set buffer size. Paste the following code:

VB.NET
Public Class Form1
Inherits Form
    Private _captureDevice As Capture 'capture device to be used
    Private _captureBuffer As CaptureBuffer 'capture buffer to capture sound
    Private _playbackDevice As Device 'sound playback device
    Private _playbackBuffer As SecondaryBuffer 'Secondary buffer to
store captured sound
    Private _bufferSize As Integer = 5000000 'capture buffer size
    Private Const _bufferPositions As Integer = 4

Next, you double click the first button, "button start". You declare a capture, the channels to be used, bits per sample, samples per second and set a wav format. You then create a secondary buffer used to store audio and a capture buffer to capture recorded audio. Overall, you start your capture buffer and recording of audio starts. The label then reflects that capturing has started. Paste the following code:

VB.NET
Private Sub ButtonStart_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles ButtonStart.Click

        _captureDevice = New Capture()

        Dim channels As Short = 1
        Dim bitsPerSample As Short = 8
        Dim samplesPerSecond As Integer = 22050

        'Set up the wave format to be captured
        Dim waveFormat As New WaveFormat()
        waveFormat.Channels = channels
        waveFormat.FormatTag = WaveFormatTag.Pcm
        waveFormat.SamplesPerSecond = samplesPerSecond
        waveFormat.BitsPerSample = bitsPerSample
        waveFormat.BlockAlign = CType((channels * (bitsPerSample / 8)), Short)
        waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign *
samplesPerSecond

        Dim captureBufferDescription As New CaptureBufferDescription()
        captureBufferDescription.BufferBytes = _bufferPositions * _bufferSize
        captureBufferDescription.Format = waveFormat
        _captureBuffer = New CaptureBuffer(captureBufferDescription,
_captureDevice)

        _playbackDevice = New Device()
        _playbackDevice.SetCooperativeLevel(Me, CooperativeLevel.Normal)

        Dim playbackBufferDescription As New BufferDescription()
        playbackBufferDescription.BufferBytes = _bufferPositions * _bufferSize
        playbackBufferDescription.Format = waveFormat
_playbackBuffer = New SecondaryBuffer(playbackBufferDescription,
_playbackDevice)

        _captureBuffer.Start(True) 'start capture buffer
               Label1.Text = "Now Capturing audio..."

    End Sub

Now that recording of audio has started, the next step is to add the code to stop audio capturing. Double click the "Stop Button". Under this button, we simply stop capture of audio by stopping the capture buffer and reflect it on the label that the capture buffer has been stopped. Paste the following code:

VB.NET
    Private Sub ButtonStop_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles ButtonStop.Click
        _captureBuffer .Stop
        Label1.Text = "Capturing stopped..."
    End Sub

Next, double click the last button which is the "Replay button". Under this button, you now copy the recorded audio from the capturebuffer to the secondary buffer for playing. The secondary buffer is played and audio starts to playback. Paste the following code.

VB.NET
    Private Sub ButtonPlay_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles ButtonPlay.Click

        Dim offset As Integer = 0
        Dim buffer As Byte() = CType(_captureBuffer.Read(offset,
GetType(Byte), LockFlag.None, _bufferSize), Byte()) 'read data in
capture buffer
        _playbackBuffer.Write(offset, buffer, LockFlag.None) 'write
data from capture buffer into secondary buffer
        _playbackBuffer.Play(0, BufferPlayFlags.Default) 'start
playing back sound
        Label1.Text = "Buffer is now Playing..."

    End Sub

Thank you for reading.

Good luck!

License

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


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

Comments and Discussions

 
Questionhow to capture sound with sound card Pin
Member 119777187-Mar-24 19:25
Member 119777187-Mar-24 19:25 
GeneralMy vote of 3 Pin
raiserle15-Oct-16 2:50
raiserle15-Oct-16 2:50 
Suggestion.Net Framework Pin
vdw26-Sep-16 15:38
vdw26-Sep-16 15:38 
QuestionThis code allow capture the sound card audio? Pin
Sergio Andrés Gutiérrez Rojas26-Sep-16 5:46
Sergio Andrés Gutiérrez Rojas26-Sep-16 5:46 

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.