📄 sound.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using WaveLib;
using System.Runtime.InteropServices;
namespace GPCore
{
internal static class Sound
{
static int threshold = 32000;
public static int THRESHOLD
{
get { return threshold; }
set { threshold = value; }
}
static WaveInRecorder mic;
static WaveOutPlayer speaker;
static WaveFormat format;
static FifoStream m_Fifo;
static int buffersize = 640;
static byte[] buffer;
public static void Initialize(int samplesize,int samplerate, int channels)
{
format = new WaveFormat(samplerate,samplesize ,channels);
mic = new WaveInRecorder(-1, format, buffersize, 3, new BufferDoneEventHandler(DataArrived));
speaker = new WaveOutPlayer(-1, format, buffersize, 3, new BufferFillEventHandler(Filler));
m_Fifo = new FifoStream();
}
public static event ByteDelegate SoundCaptured;
static bool lastpassed = false;
public static void DataArrived(IntPtr data, int size)
{
if (SoundCaptured != null)
{
buffer = new byte[size];
Marshal.Copy(data, buffer, 0, size);
long Sum = 0;
int n = size / 2;
for (int i = 0; i < n; i++)
{
int LSB = (int)buffer[2 * i];
int MSB = (int)buffer[2 * i + 1];
int Sample = ((MSB & 127) << 8) | (255 & LSB);
Sum += Sample;
}
long Avg = Sum / n;
//Higher average means LESS noise
bool passed = (Avg < threshold );
if (passed || lastpassed )
SoundCaptured(buffer);
else
Console.WriteLine("didnt pass- " + Avg);
lastpassed = passed;
}
}
public static void SoundPlayback(byte[] a)
{
if (a != null)
m_Fifo.Write(a, 0, a.Length);
}
static byte[] m_PlayBuffer;
public static void Filler(IntPtr data, int size)
{
if (m_PlayBuffer == null || m_PlayBuffer.Length < size)
m_PlayBuffer = new byte[size];
if (m_Fifo.Length >= size)
m_Fifo.Read(m_PlayBuffer, 0, size);
else
for (int i = 0; i < m_PlayBuffer.Length; i++)
m_PlayBuffer[i] = 0;
Marshal.Copy(m_PlayBuffer, 0, data, size);
}
public static void Dispose()
{
if (mic != null)
{
mic.Dispose();
mic = null;
}
if (speaker != null)
{
m_Fifo.Flush();
speaker.Dispose();
speaker = null;
}
}
}
/// <summary>
/// A delegate that has only a byte array as a parameter.
/// </summary>
/// <param name="b"></param>
public delegate void ByteDelegate(byte[] b);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -