当我在组合框上选择时,如何启用输入麦克风



我正在用Microsoft Azure制作C#窗口形式的语音到文本应用程序。我想在我的表单上有一个组合框,显示用户启用麦克风。当我选择启用麦克风并按下ok按钮时,麦克风将被选择为我选择的输入。我已经包括在组合框中,他们想使用。

如何实现这样的功能?

代码:

using System;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using System.ComponentModel;
using Microsoft.CognitiveServices.Speech;
namespace WindowsFormsApp2
{
public partial class Form2 : Form
{
[DllImport("winmm.dll", SetLastError = true)]
static extern uint waveInGetNumDevs();
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint waveInGetDevCaps(uint hwo, ref WAVEOUTCAPS pwoc, uint cbwoc);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct WAVEOUTCAPS
{
public ushort wMid;
public ushort wPid;
public uint vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string szPname;
public uint dwFormats;
public ushort wChannels;
public ushort wReserved1;
public uint dwSupport;
}
public void FillSoundDevicesInCombobox()
{
uint devices = waveInGetNumDevs();
WAVEOUTCAPS caps = new WAVEOUTCAPS();
for (uint i = 0; i < devices; i++)
{
waveInGetDevCaps(i, ref caps, (uint)Marshal.SizeOf(caps));
CB1.Items.Add(caps.szPname);
}
}

public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
FillSoundDevicesInCombobox();
// Only select the device if there is a value to load
if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.SelectedAudioDevice))
{
// find the device, matching on the value, not index
var item = CB1.Items.Cast<string>().FirstOrDefault(x => x.Equals(Properties.Settings.Default.SelectedAudioDevice));
// only select the device if we found one that matched the previous selection.
if (item != null)
CB1.SelectedItem = item;
}
checkBox1.Checked = Properties.Settings.Default.Punctuation;
//CB1.SelectedItem = Properties.Settings.Default.FillSoundDevicesInCombobox;
}
private void button1_Click(object sender, EventArgs e)
{
Properties.Settings.Default.SelectedAudioDevice = CB1.SelectedItem?.ToString();
Properties.Settings.Default.Punctuation = checkBox1.Checked;
//Properties.Settings.Default.FillSoundDevicesInCombobox = CB1.SelectedItem?.ToString();
Properties.Settings.Default.Save();
Close();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
}

您可以通过安装以下nuget包来使用Lync2013SDK:

Install-Package Lync2013SDK -Version 15.0.4466.1000

然后调用以下函数:

private void ComboBox1_SelectedIndexChanged(object sender,  System.EventArgs e)
{
ComboBox comboBox = (ComboBox) sender;
string selected = (string) ComboBox1.SelectedItem;
int i = ComboBox1.FindStringExact(selected);
var manager = LyncClient.GetClient().DeviceManager;
manager.ActiveAudioDevice = (AudioDevice)manager.AudioDevices[i];   //🠔 This is what you want
}

我建议使用Microsoft.Xna.Framework.Audio而不是interop。

这里有一个程序的例子,如果麦克风上的音量阈值被突破,它就会开始录制。我刚刚从一个大得多的项目中提取了它,所以它是不完整的,但如果你能阅读代码,它应该向你展示如何开始。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Windows.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Yeti.MMedia;
using Yeti.MMedia.Mp3;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Threading;
using LoudSoundMonitor;
using System.ComponentModel;
using System.Security;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Collections;

namespace LoudSoundMonitor
{
public partial class MainForm : Form
{
Microphone microphone = Microphone.Default;
byte[] buffer;
byte[] backBuffer;
private int minimumThreshold = 759990;
private int thresholdCount = 0;
private int thresholdCountMax = 3;
private int delayStartSeconds = 4;
private Mp3Writer mp3Writer;
private const int LSM_NotStarted = 1;
private const int LSM_Started = 2;
private const int LSM_Recording = 3;
private const int LSM_Paused = 4;
private const char LSM_Client_Transmission_Complete = 'u0004';
private int LSM_State = LSM_NotStarted;
private int prev_LSM_State;

private string loudSoundDir = System.Windows.Forms.Application.StartupPath + "\LoudSounds\";
private string baseDir = System.Windows.Forms.Application.StartupPath;
private static readonly Regex HttpPostParameterDelimiterRegex = new Regex(@"&", RegexOptions.Compiled);
private static readonly Regex HttpPostParameterRegex = new Regex(@"^(?<ParameterName>S+)=(?<ParameterValue>S*)$", RegexOptions.Compiled);


private const int ERROR_SHARING_VIOLATION = 32;
private const int ERROR_ALREADY_EXISTS = 183;

private object lameMp3EncoderLock = new object();
void microphone_BufferWrite(object sender, EventArgs e)
{
lock (lameMp3EncoderLock)
{
if (backBuffer != null)
{
mp3Writer.Write(backBuffer, 0, backBuffer.Length);
backBuffer = null;
}
else
{
mp3Writer.Write(buffer, 0, buffer.Length);
}
microphone.GetData(buffer);

if (LSM_State != LSM_Recording)
{
mp3Writer.Write(buffer, 0, buffer.Length);
mp3Writer.Close();
backBuffer = new byte[buffer.Length * thresholdCountMax];
microphone.BufferReady -= new EventHandler<EventArgs>(microphone_BufferWrite);
microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferMonitor);
}
}
}

void microphone_BufferMonitor(object sender, EventArgs e)
{
// Retrieve audio data
microphone.GetData(buffer);

// RMS Method
double rms = 0;
ushort byte1 = 0;
ushort byte2 = 0;
short value = 0;
int volume = 0;
rms = (short)(byte1 | (byte2 << 8));

for (int i = 0; i < buffer.Length - 1; i += 2)
{
byte1 = buffer[i];
byte2 = buffer[i + 1];

value = (short)(byte1 | (byte2 << 8));
rms += Math.Pow(value, 2);
}
rms /= (double)(buffer.Length / 2);
volume = (int)Math.Floor(Math.Sqrt(rms));
System.Diagnostics.Debug.WriteLine("buffer.Length" + buffer.Length + " Volume:" + volume);

if ((volume > minimumThreshold))
{

System.Buffer.BlockCopy(buffer, 0, backBuffer, thresholdCount * buffer.Length, buffer.Length);

thresholdCount++;
if (thresholdCount == thresholdCountMax)
{
thresholdCount = 0;

button1.Invoke(new System.Action(delegate()
{
button1.Text = "Recording...Press To Stop";
button1.Enabled = true;
}));

String fileName = "LoudSound_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".mp3";
if (!Directory.Exists(loudSoundDir))
{
Directory.CreateDirectory(loudSoundDir);
}
lock (lameMp3EncoderLock)
{
mp3Writer = new Mp3Writer(new FileStream(loudSoundDir + fileName, FileMode.Create), new WaveLib.WaveFormat(microphone.SampleRate, 16, 1));
}
lock (lockLSM_State)
{
LSM_State = LSM_Recording;

microphone.BufferReady -= new EventHandler<EventArgs>(microphone_BufferMonitor);
microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferWrite);
}
}
System.Diagnostics.Debug.WriteLine("Threshold exceeded");
System.Diagnostics.Debug.WriteLine("buffer.Length" + buffer.Length + " Volume:" + volume);
}
}
else
{
thresholdCount = 0;
}
}
public MainForm()
{
InitializeComponent();
microphone.BufferDuration = TimeSpan.FromMilliseconds(100);
buffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];
backBuffer = new byte[buffer.Length * thresholdCountMax];
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromMilliseconds(50);
dt.Tick += delegate(object sender, EventArgs e)
{
try { FrameworkDispatcher.Update(); }
catch { }
};
microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferMonitor);
int curInterval = 0;
System.Threading.Timer delayStart = null;
delayStart =
new System.Threading.Timer(
delegate
{
if (curInterval == delayStartSeconds)
{
dt.Start();
microphone.Start();
delayStart.Dispose();
button1.Invoke(new System.Action(delegate()
{
button1.Text = "Monitoring...";
}));
LSM_State = LSM_Started;
}
else
{
button1.Invoke(new System.Action(delegate()
{
button1.Text = "Beginning Monitoring in " + (delayStartSeconds - curInterval) + " seconds";
}));
}
curInterval++;
}
);
this.Load += delegate
{
delayStart.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
};
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Monitoring...";
button1.Enabled = false;
lock (lockLSM_State)
{
LSM_State = LSM_Started;
prev_LSM_State = 0;
if (microphone.State == MicrophoneState.Stopped)
{
microphone.Start();
}
}
}

最新更新