首页 > 解决方案 > 具有 2 个以上线程的 Visual Basic 线程

问题描述

我目前正在尝试使用自定义哔声类产生声音。beep 类的方法之一是产生具有给定频率的声音的多个八度音阶,因此一个声音是频率,另一个是频率 * 2,另一个是频率 * 4,等等。

我试图通过给每个声音自己的线程来使用线程来使所有这些声音一起发出。但是,我注意到它仍然一次播放一次声音。但是,我可以确认声音并没有中断程序本身的流程,因此线程正在以这种能力工作。

这是我正在使用的代码。这个想法是,对于NumOctave时间,基于第一个(和幅度)生成一个新频率,并设置为在其自己的线程中发声。但是,线程似乎在排队,而不是真正彼此异步执行。获得预期行为的最佳方法是什么?

Shared Sub OctBeep(ByVal Amplitude As Integer,
         ByVal Frequency As Integer, ByVal NumOctaves As Integer,
         ByVal Duration As Integer, ByVal NewThread As Boolean)

    Dim threads As List(Of Thread) = New List(Of Thread)
    Dim powTwo As Integer = 1
    Dim powTen As Integer = 1
    For oct As Integer = 1 To NumOctaves
        Dim thisOct As Integer = oct

        Dim thisThread As New Thread(
              Sub()
                  Dim newFreq, newAmp As Integer
                  newFreq = Frequency * powTwo
                  newAmp = Amplitude / powTen
                  BeepHelp(newAmp, newFreq, Duration)
              End Sub
            )

        thisThread.IsBackground = True
        thisThread.Start()

        powTwo *= 2
        powTen *= 10
    Next

End Sub

这是 BeepHelp()

Shared Sub BeepHelp(ByVal Amplitude As Integer,
         ByVal Frequency As Integer,
         ByVal Duration As Integer)

    Dim A As Double = ((Amplitude * 2 ^ 15) / 1000) - 1
    Dim DeltaFT As Double = 2 * Math.PI * Frequency / 44100

    Dim Samples As Integer = 441 * Duration \ 10
    Dim Bytes As Integer = Samples * 4
    Dim Hdr() As Integer = {&H46464952, 36 + Bytes, &H45564157,
                            &H20746D66, 16, &H20001, 44100,
                             176400, &H100004, &H61746164, Bytes}
    Using MS As New MemoryStream(44 + Bytes)
        Using BW As New BinaryWriter(MS)
            For I As Integer = 0 To Hdr.Length - 1
                BW.Write(Hdr(I))
            Next
            For T As Integer = 0 To Samples - 1
                Dim Sample As Short = CShort(A * Math.Sin(DeltaFT * T))
                BW.Write(Sample)
                BW.Write(Sample)
            Next
            BW.Flush()
            MS.Seek(0, SeekOrigin.Begin)
            Using SP As New SoundPlayer(MS)
                SP.PlaySync()
            End Using
        End Using
    End Using
End Sub

结束类

标签: vb.netmultithreading

解决方案


在编写语音合成器类之前,我遇到了同样的问题。多线程(只是移动到不同的线程,所以主程序仍然可以工作)和并行处理(将进程移动到自己的处理器)之间存在差异。您想改为研究并行处理


推荐阅读