Click here to Skip to main content
15,913,685 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why won't this close when I exit. Is VS it is still running until I hit stop.





Imports Microsoft.DirectX.DirectSound
Imports System.Threading
Imports System.Collections.Specialized
Imports Microsoft.VisualBasic.Devices
Imports Microsoft.VisualBasic
Imports System.Runtime.InteropServices


Public Class Form1
    <DllImport("winmm.dll", EntryPoint:="mciSendStringA", CharSet:=CharSet.Ansi, SetLastError:=True, ExactSpelling:=True)> Public Shared Function mciSendString(ByVal cmd As String, ByVal returnMsg As String, ByVal RetStringLen As UInt32, ByRef Hwnd As IntPtr) As Integer
    End Function

    Private Const SAMPLES As Integer = 8
    Private Shared SAMPLE_FORMAT_ARRAY As Integer() = {SAMPLES, 2, 1}
    Public Shared audioDevices As CaptureDevicesCollection
    Private Shared m_deviceNames As StringCollection

    Private deviceIndex As Integer = -1
    Private buffer As Microsoft.DirectX.DirectSound.CaptureBuffer
    Private liveVolumeThread As System.Threading.Thread
    Private m_frameDelay As Integer = 20
    Private Range_Division As Integer = 10

    'FrameDelay - the time in milliseconds between animation frames, measured in milliseconds. 
    'Values between 10 and 30 generally give good results, default is 20.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim audioDevices As New CaptureDevicesCollection
        Dim x As Integer = 0

        While x < audioDevices.Count
            ComboBox1.Items.Add(audioDevices.Item(x).Description)
            x = x + 1
        End While
        ComboBox1.SelectedIndex = 0
        Start()
        Me.Timer1.Enabled = True
        Me.Timer1.Interval = 100
        Me.Timer2.Enabled = True
        Me.Timer2.Interval = 100

        NotifyIcon1.Visible = True
        Me.WindowState = FormWindowState.Minimized
        Me.Hide()

    End Sub

    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        'Me.WindowState = FormWindowState.Minimized
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        'e.Cancel = True
        'Me.WindowState = FormWindowState.Minimized
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Start()
    End Sub

    Public Sub Start()
        [Stop]()
        Dim audioDevices As New CaptureDevicesCollection
        deviceIndex = ComboBox1.SelectedIndex
        If deviceIndex <> -1 Then
            ' initialize the capture buffer and start the animation thread
            Dim cap As New Capture(audioDevices(deviceIndex).DriverGuid)
            Dim desc As New CaptureBufferDescription()
            Dim wf As New WaveFormat()
            wf.BitsPerSample = 16
            wf.SamplesPerSecond = 44100
            wf.Channels = 2
            wf.BlockAlign = CShort(wf.Channels * wf.BitsPerSample / 8)
            wf.AverageBytesPerSecond = wf.BlockAlign * wf.SamplesPerSecond
            wf.FormatTag = WaveFormatTag.Pcm
            desc.Format = wf
            desc.BufferBytes = SAMPLES * wf.BlockAlign
            buffer = New Microsoft.DirectX.DirectSound.CaptureBuffer(desc, cap)
            buffer.Start(True)
            ' Start a seperate thread to read the buffer and update the progress bars
            liveVolumeThread = New Thread(AddressOf updateProgress)  'Thread starts at updateProgress
            Control.CheckForIllegalCrossThreadCalls = False ' This is needed otherwise the form will not update
            liveVolumeThread.Priority = ThreadPriority.Lowest ' Thread works in the background
            liveVolumeThread.Start()
        End If
    End Sub

    Public Sub [Stop]()
        If liveVolumeThread IsNot Nothing Then
            liveVolumeThread.Abort()
            liveVolumeThread.Join()
            liveVolumeThread = Nothing
        End If
        If buffer IsNot Nothing Then
            If buffer.Capturing Then
                buffer.[Stop]()
            End If
            buffer.Dispose()
            buffer = Nothing
        End If
    End Sub

    Public Sub updateProgress()
        While True
            Dim tempFrameDelay As Integer = m_frameDelay
            Dim samples__1 As Array = buffer.Read(0, GetType(Int16), LockFlag.FromWriteCursor, SAMPLE_FORMAT_ARRAY)
            Dim leftGoal As Integer = 0
            Dim rightGoal As Integer = 0
            ' Convert the 8 samples to positive values and sum them togather 
            For i As Integer = 0 To SAMPLES - 1
                If CType(samples__1.GetValue(i, 0, 0), Int16) < 0 Then
                    leftGoal -= CType(samples__1.GetValue(i, 0, 0), Int16)
                Else
                    leftGoal += CType(samples__1.GetValue(i, 0, 0), Int16)
                End If
                If CType(samples__1.GetValue(i, 1, 0), Int16) < 0 Then
                    rightGoal -= CType(samples__1.GetValue(i, 1, 0), Int16)
                Else
                    rightGoal += CType(samples__1.GetValue(i, 1, 0), Int16)
                End If
            Next
            ' Calculate the average of the 8 samples
            leftGoal = CInt(Math.Abs(leftGoal \ SAMPLES))
            rightGoal = CInt(Math.Abs(rightGoal \ SAMPLES))
            ' Convert values to deecibels
            If leftGoal = 0 Then leftGoal = 1
            If rightGoal = 0 Then rightGoal = 1
            leftGoal = (100 + (20 * Math.Log10(leftGoal / 32768)))
            rightGoal = (100 + (20 * Math.Log10(rightGoal / 32768)))
            'By adding 100 sets the display range from 0 to 100 
            'By limiting the progreess bars to 74-100 gives a viewed range of +10dB to -26dB
            'Trap the range between 74-100, giving a 26dB meter
            If leftGoal < 74 Then leftGoal = 74
            If rightGoal < 74 Then rightGoal = 74 ' Set the display range to minimum -10dB
            If leftGoal > 100 Then leftGoal = 100
            If rightGoal > 100 Then rightGoal = 100
            Dim range1 As Double = leftGoal - ProgressBar1.Value ' calculates the difference between new and the current progress bar value 
            Dim range2 As Double = rightGoal - ProgressBar2.Value
            ' Assign the exact current value of the progress bar
            Dim exactValue1 As Double = ProgressBar1.Value
            Dim exactValue2 As Double = ProgressBar2.Value
            Dim stepSize1 As Double = range1 / Range_Division
            Dim absStepSize1 As Double = Math.Abs(stepSize1)
            Dim stepSize2 As Double = range2 / Range_Division
            Dim absStepSize2 As Double = Math.Abs(stepSize2)
            If ProgressBar1.Value < leftGoal Then    ' Display the peak
                ProgressBar1.Value = leftGoal
            End If
            If ProgressBar1.Value > leftGoal Then ' decrement the value by the Range_Division
                If absStepSize1 < Math.Abs(leftGoal - ProgressBar1.Value) Then
                    exactValue1 += stepSize1
                    ProgressBar1.Value = Math.Truncate(exactValue1)
                Else
                    ProgressBar1.Value = leftGoal
                End If
            End If
            If ProgressBar2.Value < rightGoal Then
                ProgressBar2.Value = rightGoal
            End If
            If ProgressBar2.Value > rightGoal Then ' decrement the value by the Range_Division
                If absStepSize2 < Math.Abs(rightGoal - ProgressBar2.Value) Then
                    exactValue2 += stepSize2
                    ProgressBar2.Value = Math.Truncate(exactValue2)
                Else
                    ProgressBar2.Value = rightGoal
                End If
            End If
            Thread.Sleep(m_frameDelay)
        End While
    End Sub

    Public Sub Record()
        Dim result As Long
        Try
            result = mciSendString("open new Type waveaudio Alias recsound", "", 0, Nothing)
            result = mciSendString("record recsound", "", 0, 0)
        Catch ex As Exception
        End Try
    End Sub

    Public Function CloseAudio()
        mciSendString("close all", 0, 0, 0)
    End Function


    Public Sub StopAndSave()
        Dim formatteddate As String
        formatteddate = DateTime.Now.ToString("MMddyyyyHHmmss")
        Dim Filetosave As String = "save recsound " & ("\\bsppd4wiswalld\Recorder" & "\" & formatteddate & ".wav")
        'Dim Filetosave As String = "save recsound " & ("C:\Recorder" & "\" & formatteddate & ".wav")
        mciSendString(Filetosave, "", 0, 0)
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Me.ProgressBar2.Value >= 80 Then
            Record()
        ElseIf Me.ProgressBar2.Value < 80 Then
            Me.Timer1.Enabled = True
        End If
    End Sub

    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        If Me.ProgressBar2.Value < 80 Then
            Me.Timer1.Enabled = False
            StopAndSave()
            CloseAudio()
        Else
        End If
        Me.Timer1.Enabled = True
    End Sub

    Private Sub RestoreToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RestoreToolStripMenuItem.Click
        Me.WindowState = FormWindowState.Normal
    End Sub

    Private Sub PlayToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PlayToolStripMenuItem.Click
        frmPlay.Show()
        Dim openfiledialog1 As New OpenFileDialog
        openfiledialog1.InitialDirectory = "C:\"
        'openfiledialog1.InitialDirectory = "\\Bsppd4wiswalld\Recorder"
        openfiledialog1.Filter = "WAV Files (*.wav)|*.wav"
        openfiledialog1.ShowDialog()
        frmPlay.AxWindowsMediaPlayer1.URL = openfiledialog1.FileName
        Me.Stop()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        CloseAudio()
        [Stop]()
        Application.Exit()
        NotifyIcon1.Visible = False
    End Sub
End Class
Posted
Updated 3-Aug-10 11:45am
v4
Comments
Dalek Dave 3-Aug-10 9:12am    
Edited for Code Block.

You can also use set the IsBackground property for non ui threads

e.g
MIDL
liveVolumeThread.IsBackground = true;


http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx[^]

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.
 
Share this answer
 
People will not be willing to trawl through three million lines of code just to help you out with a small problem.

Explain where you think it is going wrong and only show the pertinent area of code.

That much code is disconcerting.
 
Share this answer
 
Most likely you haven't ended threads correctly.

Make sure you've destroyed all your objects and cleaned everything up as best you can
 
Share this answer
 
I think it may be here. I am sorry you are right I hate when people post 8 million lines of code.

VB
Public Sub [Stop]()
       If liveVolumeThread IsNot Nothing Then
           liveVolumeThread.Abort()
           liveVolumeThread.Join()
           liveVolumeThread = Nothing
       End If
       If buffer IsNot Nothing Then
           If buffer.Capturing Then
               buffer.[Stop]()
           End If
           buffer.Dispose()
           buffer = Nothing
       End If
   End Sub



VB
Public Function CloseAudio()
      mciSendString("close all", 0, 0, 0)
  End Function
 
Share this answer
 
I am definitely not going to look through all your code, but my first guess would be, since you have the line me.hide in your form-load-event, you simply have the main-window runing hidden, even if you think, the programme should have finished.
But I really wouldn't know, since this is far too much code to even bother having a closer look at it.
 
Share this answer
 
I think it was in this I added
VB
liveVolumeThread.Suspend()
        buffer.Dispose()


and it seems to work


VB
Public Sub Start()
    [Stop]()
    Dim audioDevices As New CaptureDevicesCollection
    deviceIndex = ComboBox1.SelectedIndex
    If deviceIndex <> -1 Then
        ' initialize the capture buffer and start the animation thread
        Dim cap As New Capture(audioDevices(deviceIndex).DriverGuid)
        Dim desc As New CaptureBufferDescription()
        Dim wf As New WaveFormat()
        wf.BitsPerSample = 16
        wf.SamplesPerSecond = 44100
        wf.Channels = 2
        wf.BlockAlign = CShort(wf.Channels * wf.BitsPerSample / 8)
        wf.AverageBytesPerSecond = wf.BlockAlign * wf.SamplesPerSecond
        wf.FormatTag = WaveFormatTag.Pcm
        desc.Format = wf
        desc.BufferBytes = SAMPLES * wf.BlockAlign
        buffer = New Microsoft.DirectX.DirectSound.CaptureBuffer(desc, cap)
        buffer.Start(True)
        ' Start a seperate thread to read the buffer and update the progress bars
        liveVolumeThread = New Thread(AddressOf updateProgress)  'Thread starts at updateProgress
        Control.CheckForIllegalCrossThreadCalls = False ' This is needed otherwise the form will not update
        liveVolumeThread.Priority = ThreadPriority.Lowest ' Thread works in the background
        liveVolumeThread.Start()
    End If
End Sub
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900