SafeDispatch/SafeMobileLIB_DLL/Audio.cs
2024-02-22 18:43:59 +02:00

90 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SafeMobileLib
{
public class test_NewAudio
{
private WaveOutPlayer m_Player;
private WaveInRecorder m_Recorder;
public FifoStream m_Fifo = new FifoStream();
private byte[] m_PlayBuffer;
private byte[] m_RecBuffer;
private int inDevID;
private int outDevID;
public test_NewAudio(int _inDevID , int _outDevID)
{
Utils.WriteLine("Create newAudio IN:"+_inDevID+" OUT:"+_outDevID,ConsoleColor.Blue);
inDevID = _inDevID;
outDevID = _outDevID;
//WaveFormat fmt = new WaveFormat(44100, 16, 1);
WaveFormat fmt = new WaveFormat(8000, 16, 1);//44100 //2048 //8192
m_Player = new WaveOutPlayer(outDevID, fmt, 512, 6, new BufferFillEventHandler(Filler));//16384
m_Recorder = new WaveInRecorder(inDevID, fmt, 512, 6, new BufferDoneEventHandler(Voice_Out));//16384
}
public void PlaySound(byte[] data, int len)
{
m_Fifo.Write(data, 0, len);
}
private 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;
System.Runtime.InteropServices.Marshal.Copy(m_PlayBuffer, 0, data, size);
// m_Fifo ==> m_PlayBuffer==> data ==> Speakers
}
private void Voice_Out(IntPtr data, int size)
{
//for Recorder
if (m_RecBuffer == null || m_RecBuffer.Length < size)
m_RecBuffer = new byte[size];
System.Runtime.InteropServices.Marshal.Copy(data, m_RecBuffer, 0, size);
if (this.OnVoiceRecv != null)
{
this.OnVoiceRecv(m_RecBuffer, m_RecBuffer.Length);
}
}
public delegate void VoiceRecv(byte[] data, int recv);
public event VoiceRecv OnVoiceRecv;
public void Dispose()
{
Console.WriteLine("Begin Dispose");
if (m_Player != null)
try
{
m_Player.Dispose();
}
finally
{
m_Player = null;
}
Console.WriteLine("After Player");
if (m_Recorder != null)
try
{
m_Recorder.Dispose();
}
finally
{
m_Recorder = null;
}
Console.WriteLine("After record");
m_Fifo.Flush();
Console.WriteLine("End Dispose");
}
}
}