如何录制扬声器的音频?

Posted

技术标签:

【中文标题】如何录制扬声器的音频?【英文标题】:How do I record audio from speakers? 【发布时间】:2016-05-07 06:03:50 【问题描述】:
Imports NAudio
Imports System.IO
Imports NAudio.Utils

Public Class Form1
    Private waveSource As Wave.WaveIn = Nothing
    Private waveFile As Wave.WaveFileWriter = Nothing
    Private waveFileWriter As Wave.WaveFileWriter
    Dim ms As MemoryStream

    Private Sub waveSource_DataAvailable(ByVal sender As Object, ByVal e As Wave.WaveInEventArgs)
        waveFileWriter.Write(e.Buffer, 0, e.BytesRecorded)
        waveFileWriter.Flush()
    End Sub

    Private Sub waveSource_RecordingStopped(ByVal sender As Object, ByVal e As Wave.StoppedEventArgs)
        Dim fs As FileStream = File.Create(Environment.CurrentDirectory & "\test.wav")
        ms.Seek(0, SeekOrigin.Begin)
        ms.CopyTo(fs)
    End Sub

    Private Sub startBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startBTN.Click
        ms = New MemoryStream()

        waveFileWriter = New Wave.WaveFileWriter(New IgnoreDisposeStream(ms), waveSource.WaveFormat)
        waveSource.StartRecording()
    End Sub

    Private Sub stopBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles stopBTN.Click
        waveSource.StopRecording()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        waveSource = New Wave.WaveIn

        AddHandler waveSource.DataAvailable, AddressOf waveSource_DataAvailable
        AddHandler waveSource.RecordingStopped, AddressOf waveSource_RecordingStopped
    End Sub
End Class

翻译以下帖子中的代码,这会引发“Bad Device ID”异常。

Naudio Recording and playing audio

我没有任何录音设备(或 WaveIn)。是这个原因吗?

【问题讨论】:

【参考方案1】:

是的。 NAudio 是开源的。您可以调试它并自己发现它。

调查 WASAPI 捕获。我不知道这是否可行,但这是下一步。

【讨论】:

【参考方案2】:

C# how to record general audio from output device ( speaker ) with NAudio API

    Private waveSource As Wave.WasapiLoopbackCapture = Nothing

Wave.WaveIn 更改为Wave.WasapiLoopbackCapture 解决了我的问题。当然,我的代码仍然存在问题(请注意)。点击停止会停止捕获但不写入文件。只有在您强制退出应用程序之前,.wav 才会保存到磁盘。我可以自己解决。

【讨论】:

【参考方案3】:

将此添加到Private Sub waveSource_RecordingStopped 以在不关闭应用程序的情况下查看.wav

fs.Dispose()

【讨论】:

以上是关于如何录制扬声器的音频?的主要内容,如果未能解决你的问题,请参考以下文章

Windows Phone 8 录制扬声器音频

从无线耳机录制音频并通过蓝牙扬声器播放

如何在 iPhone 扬声器上强制播放音频?

在 iphone/ipad 扬声器中录制音频

iOS 无法在扬声器上播放并将音频会话设置为录制

仅从 iphone 扬声器(不包括麦克风)录制音频输出