diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/DataService/AudioServiceImpl.cs b/Correlator/DataService/AudioServiceImpl.cs
index 12bfc7a..73c2f7e 100644
--- a/Correlator/DataService/AudioServiceImpl.cs
+++ b/Correlator/DataService/AudioServiceImpl.cs
@@ -1,4 +1,5 @@
using System;
+using Correlator.Util;
using NAudio.Wave;
namespace Correlator.DataService
@@ -18,10 +19,8 @@
_waveOut.Init(_lazyWaveProvider.Value);
_waveOut.Play();
- // var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
- // _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
- // var fileHeader = AudioHub.CreateWaveFileHeader(int.MaxValue, 7500, 16, 1);
- // _waveFileWriter.Write(fileHeader, 0, fileHeader.Length);
+ var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
+ _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
}
public void Write(byte[] pcm)
@@ -29,20 +28,20 @@
_lazyWaveProvider.Value.AddSamples(pcm, 0, pcm.Length);
//将pcm数据保存为wav格式文件
- // if (_waveFileWriter == null)
- // {
- // return;
- // }
- //
- // _waveFileWriter.Write(pcm, 0, pcm.Length);
+ if (_waveFileWriter == null)
+ {
+ return;
+ }
+
+ _waveFileWriter.Write(pcm, 0, pcm.Length);
}
public void Stop()
{
_waveOut.Stop();
- // _waveFileWriter.Dispose();
- // _waveFileWriter = null;
+ _waveFileWriter.Dispose();
+ _waveFileWriter = null;
}
}
}
\ No newline at end of file
diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/DataService/AudioServiceImpl.cs b/Correlator/DataService/AudioServiceImpl.cs
index 12bfc7a..73c2f7e 100644
--- a/Correlator/DataService/AudioServiceImpl.cs
+++ b/Correlator/DataService/AudioServiceImpl.cs
@@ -1,4 +1,5 @@
using System;
+using Correlator.Util;
using NAudio.Wave;
namespace Correlator.DataService
@@ -18,10 +19,8 @@
_waveOut.Init(_lazyWaveProvider.Value);
_waveOut.Play();
- // var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
- // _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
- // var fileHeader = AudioHub.CreateWaveFileHeader(int.MaxValue, 7500, 16, 1);
- // _waveFileWriter.Write(fileHeader, 0, fileHeader.Length);
+ var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
+ _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
}
public void Write(byte[] pcm)
@@ -29,20 +28,20 @@
_lazyWaveProvider.Value.AddSamples(pcm, 0, pcm.Length);
//将pcm数据保存为wav格式文件
- // if (_waveFileWriter == null)
- // {
- // return;
- // }
- //
- // _waveFileWriter.Write(pcm, 0, pcm.Length);
+ if (_waveFileWriter == null)
+ {
+ return;
+ }
+
+ _waveFileWriter.Write(pcm, 0, pcm.Length);
}
public void Stop()
{
_waveOut.Stop();
- // _waveFileWriter.Dispose();
- // _waveFileWriter = null;
+ _waveFileWriter.Dispose();
+ _waveFileWriter = null;
}
}
}
\ No newline at end of file
diff --git a/Correlator/Util/PlayWav.cs b/Correlator/Util/PlayWav.cs
deleted file mode 100644
index a54ba0d..0000000
--- a/Correlator/Util/PlayWav.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace Correlator.Util
-{
- public class PlayWav
- {
- private WaveOut _wavPlayer;
-
- private WaveFormat _wavFormat;
-
- private bool _isPlaying;
- private WaveOutStream _waveOutStream;
-
- #region 单例
-
- private static readonly Lazy Lazy = new Lazy(() => new PlayWav());
-
- public static PlayWav Get => Lazy.Value;
-
- private PlayWav()
- {
- }
-
- #endregion
-
- public void InitWaveOut()
- {
- if (_isPlaying)
- {
- Stop();
- }
-
- try
- {
- //必须填入文件名,否则ws无法实例化
- var ws = new WaveOutStream(
- $"{DirectoryManager.GetAudioDir()}/Audio_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav"
- );
- _waveOutStream = ws;
- _waveOutStream.Position = 0;
- _wavFormat = ws.Format;
-
- _wavPlayer = new WaveOut(-1, _wavFormat, _wavFormat.nAvgBytesPerSec, 20, StreamBufferFiller);
- _isPlaying = true;
- }
- catch (Exception e)
- {
- "PlayWav".WriteLog(e.Message);
- }
- }
-
- public void Stop()
- {
- if (_wavPlayer == null) return;
-
- _wavPlayer.Dispose();
- _wavPlayer = null;
-
- //TODO 待优化。每次点击结束听音,但是While循环并没有立即结束,所以循环会直接报错
- if (_waveOutStream == null) return;
-
- _waveOutStream.Close();
- _waveOutStream = null;
- }
-
- public void Listen(byte[] bytesData)
- {
- var receiveBytesNum = bytesData.Length;
- if (_waveOutStream == null) return;
- lock (this)
- {
- _waveOutStream.Write(bytesData, 0, receiveBytesNum);
- }
- }
-
- private void StreamBufferFiller(IntPtr data, int size)
- {
- var buffer = new byte[size];
- if (_waveOutStream != null)
- {
- var pos = 0;
- while (pos < size)
- {
- var totalGet = size - pos;
- var got = _waveOutStream.Read(buffer, pos, totalGet);
- if (got <= 0)
- {
- Thread.Sleep(1000);
- }
-
- if (got < totalGet)
- {
- _waveOutStream.Position = 0; // loop if the file ends
- }
-
- pos += got;
- }
- }
- else
- {
- for (var i = 0; i < buffer.Length; i++)
- {
- buffer[i] = 0;
- }
- }
-
- Marshal.Copy(buffer, 0, data, size);
- }
-
- private void Dispose()
- {
- if (_wavPlayer == null) return;
- try
- {
- _wavPlayer.Dispose();
- }
- finally
- {
- _wavPlayer = null;
- }
- }
-
- ~PlayWav()
- {
- Dispose();
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/DataService/AudioServiceImpl.cs b/Correlator/DataService/AudioServiceImpl.cs
index 12bfc7a..73c2f7e 100644
--- a/Correlator/DataService/AudioServiceImpl.cs
+++ b/Correlator/DataService/AudioServiceImpl.cs
@@ -1,4 +1,5 @@
using System;
+using Correlator.Util;
using NAudio.Wave;
namespace Correlator.DataService
@@ -18,10 +19,8 @@
_waveOut.Init(_lazyWaveProvider.Value);
_waveOut.Play();
- // var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
- // _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
- // var fileHeader = AudioHub.CreateWaveFileHeader(int.MaxValue, 7500, 16, 1);
- // _waveFileWriter.Write(fileHeader, 0, fileHeader.Length);
+ var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
+ _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
}
public void Write(byte[] pcm)
@@ -29,20 +28,20 @@
_lazyWaveProvider.Value.AddSamples(pcm, 0, pcm.Length);
//将pcm数据保存为wav格式文件
- // if (_waveFileWriter == null)
- // {
- // return;
- // }
- //
- // _waveFileWriter.Write(pcm, 0, pcm.Length);
+ if (_waveFileWriter == null)
+ {
+ return;
+ }
+
+ _waveFileWriter.Write(pcm, 0, pcm.Length);
}
public void Stop()
{
_waveOut.Stop();
- // _waveFileWriter.Dispose();
- // _waveFileWriter = null;
+ _waveFileWriter.Dispose();
+ _waveFileWriter = null;
}
}
}
\ No newline at end of file
diff --git a/Correlator/Util/PlayWav.cs b/Correlator/Util/PlayWav.cs
deleted file mode 100644
index a54ba0d..0000000
--- a/Correlator/Util/PlayWav.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace Correlator.Util
-{
- public class PlayWav
- {
- private WaveOut _wavPlayer;
-
- private WaveFormat _wavFormat;
-
- private bool _isPlaying;
- private WaveOutStream _waveOutStream;
-
- #region 单例
-
- private static readonly Lazy Lazy = new Lazy(() => new PlayWav());
-
- public static PlayWav Get => Lazy.Value;
-
- private PlayWav()
- {
- }
-
- #endregion
-
- public void InitWaveOut()
- {
- if (_isPlaying)
- {
- Stop();
- }
-
- try
- {
- //必须填入文件名,否则ws无法实例化
- var ws = new WaveOutStream(
- $"{DirectoryManager.GetAudioDir()}/Audio_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav"
- );
- _waveOutStream = ws;
- _waveOutStream.Position = 0;
- _wavFormat = ws.Format;
-
- _wavPlayer = new WaveOut(-1, _wavFormat, _wavFormat.nAvgBytesPerSec, 20, StreamBufferFiller);
- _isPlaying = true;
- }
- catch (Exception e)
- {
- "PlayWav".WriteLog(e.Message);
- }
- }
-
- public void Stop()
- {
- if (_wavPlayer == null) return;
-
- _wavPlayer.Dispose();
- _wavPlayer = null;
-
- //TODO 待优化。每次点击结束听音,但是While循环并没有立即结束,所以循环会直接报错
- if (_waveOutStream == null) return;
-
- _waveOutStream.Close();
- _waveOutStream = null;
- }
-
- public void Listen(byte[] bytesData)
- {
- var receiveBytesNum = bytesData.Length;
- if (_waveOutStream == null) return;
- lock (this)
- {
- _waveOutStream.Write(bytesData, 0, receiveBytesNum);
- }
- }
-
- private void StreamBufferFiller(IntPtr data, int size)
- {
- var buffer = new byte[size];
- if (_waveOutStream != null)
- {
- var pos = 0;
- while (pos < size)
- {
- var totalGet = size - pos;
- var got = _waveOutStream.Read(buffer, pos, totalGet);
- if (got <= 0)
- {
- Thread.Sleep(1000);
- }
-
- if (got < totalGet)
- {
- _waveOutStream.Position = 0; // loop if the file ends
- }
-
- pos += got;
- }
- }
- else
- {
- for (var i = 0; i < buffer.Length; i++)
- {
- buffer[i] = 0;
- }
- }
-
- Marshal.Copy(buffer, 0, data, size);
- }
-
- private void Dispose()
- {
- if (_wavPlayer == null) return;
- try
- {
- _wavPlayer.Dispose();
- }
- finally
- {
- _wavPlayer = null;
- }
- }
-
- ~PlayWav()
- {
- Dispose();
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOut.cs b/Correlator/Util/WaveOut.cs
deleted file mode 100644
index df51931..0000000
--- a/Correlator/Util/WaveOut.cs
+++ /dev/null
@@ -1,288 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Correlator.Util
-{
- internal static class WaveOutHelper
- {
- public static void Try(int err)
- {
- if (err != WaveOutBase.MmsyserrNoerror)
- throw new Exception(err.ToString());
- }
- }
-
- public delegate void BufferFillEventHandler(IntPtr data, int size);
-
- internal class WaveOutBuffer : IDisposable
- {
- public WaveOutBuffer NextBuffer;
-
- private readonly AutoResetEvent _mPlayEvent = new AutoResetEvent(false);
- private readonly IntPtr _mWaveOut;
-
- private WaveOutBase.WaveHdr _mHeader;
- private GCHandle _mHeaderHandle;
- private GCHandle _mHeaderDataHandle;
-
- private int _mark;
-
- private bool _mPlaying;
-
- internal static void WaveOutProc(IntPtr hdrvr, int uMsg, int dwUser, ref WaveOutBase.WaveHdr wavhdr,
- int dwParam2)
- {
- if (uMsg != WaveOutBase.MmWomDone) return;
- try
- {
- var h = (GCHandle)wavhdr.dwUser;
- var buf = (WaveOutBuffer)h.Target;
- buf.OnCompleted();
- }
- catch (Exception e)
- {
- "WaveOut".WriteLog(e.Message);
- }
- }
-
- public WaveOutBuffer(IntPtr waveOutHandle, int size)
- {
- _mWaveOut = waveOutHandle;
-
- _mHeaderHandle = GCHandle.Alloc(_mHeader, GCHandleType.Pinned);
- _mHeader.dwUser = (IntPtr)GCHandle.Alloc(this);
- var mHeaderData = new byte[size];
- _mHeaderDataHandle = GCHandle.Alloc(mHeaderData, GCHandleType.Pinned);
- _mHeader.lpData = _mHeaderDataHandle.AddrOfPinnedObject();
- _mHeader.dwBufferLength = size;
- WaveOutHelper.Try(WaveOutBase.waveOutPrepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)));
- }
-
- public void Set(int mark)
- {
- _mark = mark;
- }
-
- ~WaveOutBuffer()
- {
- Dispose();
- }
-
- public void Dispose()
- {
- if (_mHeader.lpData != IntPtr.Zero)
- {
- WaveOutBase.waveOutUnprepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader));
- _mHeaderHandle.Free();
- _mHeader.lpData = IntPtr.Zero;
- }
-
- _mPlayEvent.Close();
- if (_mHeaderDataHandle.IsAllocated)
- _mHeaderDataHandle.Free();
- GC.SuppressFinalize(this);
- }
-
- public int Size => _mHeader.dwBufferLength;
-
- public IntPtr Data => _mHeader.lpData;
-
- private void GetMemory(string title)
- {
- "WaveOut".WriteLog($"{title}: {_mPlaying}, {_mark}");
- }
-
- public bool Play()
- {
- lock (this)
- {
- GetMemory("Play");
- _mPlayEvent.Reset();
- _mPlaying = WaveOutBase.waveOutWrite(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)) ==
- WaveOutBase.MmsyserrNoerror;
- return _mPlaying;
- }
- }
-
- public void WaitFor()
- {
- GetMemory("WaitFor");
- if (_mPlaying)
- {
- _mPlaying = _mPlayEvent.WaitOne();
- }
- }
-
- private void OnCompleted()
- {
- GetMemory("OnCompleted");
- _mPlayEvent.Set();
- _mPlaying = false;
- }
- }
-
- public class WaveOut : IDisposable
- {
- private IntPtr _mWaveOut;
- private WaveOutBuffer _mBuffers; // linked list
- private WaveOutBuffer _mCurrentBuffer;
- private Task _mThread;
- private BufferFillEventHandler _mFillProc;
- private bool _mFinished;
-
- private bool _mPause;
-
- //public bool bPause
- //{
- // get { return m_Pause; }
- // set { m_Pause = value; }
- //}
- private readonly byte _mZero;
-
- private readonly WaveOutBase.WaveDelegate _mBufferProc = WaveOutBuffer.WaveOutProc;
-
- public static int DeviceCount => WaveOutBase.waveOutGetNumDevs();
-
- public WaveOut(int device, WaveFormat format, int bufferSize, int bufferCount, BufferFillEventHandler fillProc)
- {
- _mZero = format.wBitsPerSample == 8 ? (byte)128 : (byte)0;
- _mFillProc = fillProc;
- WaveOutHelper.Try(WaveOutBase.waveOutOpen(out _mWaveOut, device, format, _mBufferProc, 0,
- WaveOutBase.CallbackFunction));
- AllocateBuffers(bufferSize, bufferCount);
-
- _mThread = new Task(ThreadProc);
- _mThread.Start();
- }
-
- ~WaveOut()
- {
- Dispose();
- }
-
- public void Pause()
- {
- _mPause = true;
- WaveOutBase.waveOutPause(_mWaveOut);
- //WaveOutBase.waveOutReset(m_WaveOut);
- }
-
- public void Resume()
- {
- _mPause = false;
- WaveOutBase.waveOutRestart(_mWaveOut);
- }
-
- public void Dispose()
- {
- if (_mThread != null)
- try
- {
- _mPause = false;
- _mFinished = true;
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutReset(_mWaveOut);
-
- _mFillProc = null;
- FreeBuffers();
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutClose(_mWaveOut);
- }
- finally
- {
- _mThread = null;
- _mWaveOut = IntPtr.Zero;
- }
-
- GC.SuppressFinalize(this);
- }
-
- private void ThreadProc()
- {
- _mPause = false;
- while (!_mFinished)
- {
- // pause
- while (_mPause)
- {
- Thread.Sleep(10);
- }
-
- Advance();
- if (_mFillProc != null && !_mFinished)
- {
- _mFillProc(_mCurrentBuffer.Data, _mCurrentBuffer.Size);
- }
- else if (_mCurrentBuffer != null)
- {
- // zero out buffer
- var b = new byte[_mCurrentBuffer.Size];
- for (var i = 0; i < b.Length; i++)
- b[i] = _mZero;
- Marshal.Copy(b, 0, _mCurrentBuffer.Data, b.Length);
- }
-
- _mCurrentBuffer?.Play();
- }
-
- WaitForAllBuffers();
- }
-
- private void AllocateBuffers(int bufferSize, int bufferCount)
- {
- FreeBuffers();
- if (bufferCount <= 0) return;
- _mBuffers = new WaveOutBuffer(_mWaveOut, bufferSize);
- _mBuffers.Set(0);
- var prev = _mBuffers;
- try
- {
- for (var i = 1; i < bufferCount; i++)
- {
- var buf = new WaveOutBuffer(_mWaveOut, bufferSize);
- buf.Set(i);
- prev.NextBuffer = buf;
- prev = buf;
- }
- }
- finally
- {
- prev.NextBuffer = _mBuffers;
- }
- }
-
- private void FreeBuffers()
- {
- _mCurrentBuffer = null;
- if (_mBuffers == null) return;
- var first = _mBuffers;
- _mBuffers = null;
-
- var current = first;
- do
- {
- var next = current.NextBuffer;
- current.Dispose();
- current = next;
- } while (current != first);
- }
-
- private void Advance()
- {
- _mCurrentBuffer = _mCurrentBuffer == null ? _mBuffers : _mCurrentBuffer.NextBuffer;
- _mCurrentBuffer?.WaitFor();
- }
-
- private void WaitForAllBuffers()
- {
- var buf = _mBuffers;
- while (_mBuffers != null && buf.NextBuffer != _mBuffers)
- {
- buf.WaitFor();
- buf = buf.NextBuffer;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/DataService/AudioServiceImpl.cs b/Correlator/DataService/AudioServiceImpl.cs
index 12bfc7a..73c2f7e 100644
--- a/Correlator/DataService/AudioServiceImpl.cs
+++ b/Correlator/DataService/AudioServiceImpl.cs
@@ -1,4 +1,5 @@
using System;
+using Correlator.Util;
using NAudio.Wave;
namespace Correlator.DataService
@@ -18,10 +19,8 @@
_waveOut.Init(_lazyWaveProvider.Value);
_waveOut.Play();
- // var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
- // _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
- // var fileHeader = AudioHub.CreateWaveFileHeader(int.MaxValue, 7500, 16, 1);
- // _waveFileWriter.Write(fileHeader, 0, fileHeader.Length);
+ var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
+ _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
}
public void Write(byte[] pcm)
@@ -29,20 +28,20 @@
_lazyWaveProvider.Value.AddSamples(pcm, 0, pcm.Length);
//将pcm数据保存为wav格式文件
- // if (_waveFileWriter == null)
- // {
- // return;
- // }
- //
- // _waveFileWriter.Write(pcm, 0, pcm.Length);
+ if (_waveFileWriter == null)
+ {
+ return;
+ }
+
+ _waveFileWriter.Write(pcm, 0, pcm.Length);
}
public void Stop()
{
_waveOut.Stop();
- // _waveFileWriter.Dispose();
- // _waveFileWriter = null;
+ _waveFileWriter.Dispose();
+ _waveFileWriter = null;
}
}
}
\ No newline at end of file
diff --git a/Correlator/Util/PlayWav.cs b/Correlator/Util/PlayWav.cs
deleted file mode 100644
index a54ba0d..0000000
--- a/Correlator/Util/PlayWav.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace Correlator.Util
-{
- public class PlayWav
- {
- private WaveOut _wavPlayer;
-
- private WaveFormat _wavFormat;
-
- private bool _isPlaying;
- private WaveOutStream _waveOutStream;
-
- #region 单例
-
- private static readonly Lazy Lazy = new Lazy(() => new PlayWav());
-
- public static PlayWav Get => Lazy.Value;
-
- private PlayWav()
- {
- }
-
- #endregion
-
- public void InitWaveOut()
- {
- if (_isPlaying)
- {
- Stop();
- }
-
- try
- {
- //必须填入文件名,否则ws无法实例化
- var ws = new WaveOutStream(
- $"{DirectoryManager.GetAudioDir()}/Audio_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav"
- );
- _waveOutStream = ws;
- _waveOutStream.Position = 0;
- _wavFormat = ws.Format;
-
- _wavPlayer = new WaveOut(-1, _wavFormat, _wavFormat.nAvgBytesPerSec, 20, StreamBufferFiller);
- _isPlaying = true;
- }
- catch (Exception e)
- {
- "PlayWav".WriteLog(e.Message);
- }
- }
-
- public void Stop()
- {
- if (_wavPlayer == null) return;
-
- _wavPlayer.Dispose();
- _wavPlayer = null;
-
- //TODO 待优化。每次点击结束听音,但是While循环并没有立即结束,所以循环会直接报错
- if (_waveOutStream == null) return;
-
- _waveOutStream.Close();
- _waveOutStream = null;
- }
-
- public void Listen(byte[] bytesData)
- {
- var receiveBytesNum = bytesData.Length;
- if (_waveOutStream == null) return;
- lock (this)
- {
- _waveOutStream.Write(bytesData, 0, receiveBytesNum);
- }
- }
-
- private void StreamBufferFiller(IntPtr data, int size)
- {
- var buffer = new byte[size];
- if (_waveOutStream != null)
- {
- var pos = 0;
- while (pos < size)
- {
- var totalGet = size - pos;
- var got = _waveOutStream.Read(buffer, pos, totalGet);
- if (got <= 0)
- {
- Thread.Sleep(1000);
- }
-
- if (got < totalGet)
- {
- _waveOutStream.Position = 0; // loop if the file ends
- }
-
- pos += got;
- }
- }
- else
- {
- for (var i = 0; i < buffer.Length; i++)
- {
- buffer[i] = 0;
- }
- }
-
- Marshal.Copy(buffer, 0, data, size);
- }
-
- private void Dispose()
- {
- if (_wavPlayer == null) return;
- try
- {
- _wavPlayer.Dispose();
- }
- finally
- {
- _wavPlayer = null;
- }
- }
-
- ~PlayWav()
- {
- Dispose();
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOut.cs b/Correlator/Util/WaveOut.cs
deleted file mode 100644
index df51931..0000000
--- a/Correlator/Util/WaveOut.cs
+++ /dev/null
@@ -1,288 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Correlator.Util
-{
- internal static class WaveOutHelper
- {
- public static void Try(int err)
- {
- if (err != WaveOutBase.MmsyserrNoerror)
- throw new Exception(err.ToString());
- }
- }
-
- public delegate void BufferFillEventHandler(IntPtr data, int size);
-
- internal class WaveOutBuffer : IDisposable
- {
- public WaveOutBuffer NextBuffer;
-
- private readonly AutoResetEvent _mPlayEvent = new AutoResetEvent(false);
- private readonly IntPtr _mWaveOut;
-
- private WaveOutBase.WaveHdr _mHeader;
- private GCHandle _mHeaderHandle;
- private GCHandle _mHeaderDataHandle;
-
- private int _mark;
-
- private bool _mPlaying;
-
- internal static void WaveOutProc(IntPtr hdrvr, int uMsg, int dwUser, ref WaveOutBase.WaveHdr wavhdr,
- int dwParam2)
- {
- if (uMsg != WaveOutBase.MmWomDone) return;
- try
- {
- var h = (GCHandle)wavhdr.dwUser;
- var buf = (WaveOutBuffer)h.Target;
- buf.OnCompleted();
- }
- catch (Exception e)
- {
- "WaveOut".WriteLog(e.Message);
- }
- }
-
- public WaveOutBuffer(IntPtr waveOutHandle, int size)
- {
- _mWaveOut = waveOutHandle;
-
- _mHeaderHandle = GCHandle.Alloc(_mHeader, GCHandleType.Pinned);
- _mHeader.dwUser = (IntPtr)GCHandle.Alloc(this);
- var mHeaderData = new byte[size];
- _mHeaderDataHandle = GCHandle.Alloc(mHeaderData, GCHandleType.Pinned);
- _mHeader.lpData = _mHeaderDataHandle.AddrOfPinnedObject();
- _mHeader.dwBufferLength = size;
- WaveOutHelper.Try(WaveOutBase.waveOutPrepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)));
- }
-
- public void Set(int mark)
- {
- _mark = mark;
- }
-
- ~WaveOutBuffer()
- {
- Dispose();
- }
-
- public void Dispose()
- {
- if (_mHeader.lpData != IntPtr.Zero)
- {
- WaveOutBase.waveOutUnprepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader));
- _mHeaderHandle.Free();
- _mHeader.lpData = IntPtr.Zero;
- }
-
- _mPlayEvent.Close();
- if (_mHeaderDataHandle.IsAllocated)
- _mHeaderDataHandle.Free();
- GC.SuppressFinalize(this);
- }
-
- public int Size => _mHeader.dwBufferLength;
-
- public IntPtr Data => _mHeader.lpData;
-
- private void GetMemory(string title)
- {
- "WaveOut".WriteLog($"{title}: {_mPlaying}, {_mark}");
- }
-
- public bool Play()
- {
- lock (this)
- {
- GetMemory("Play");
- _mPlayEvent.Reset();
- _mPlaying = WaveOutBase.waveOutWrite(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)) ==
- WaveOutBase.MmsyserrNoerror;
- return _mPlaying;
- }
- }
-
- public void WaitFor()
- {
- GetMemory("WaitFor");
- if (_mPlaying)
- {
- _mPlaying = _mPlayEvent.WaitOne();
- }
- }
-
- private void OnCompleted()
- {
- GetMemory("OnCompleted");
- _mPlayEvent.Set();
- _mPlaying = false;
- }
- }
-
- public class WaveOut : IDisposable
- {
- private IntPtr _mWaveOut;
- private WaveOutBuffer _mBuffers; // linked list
- private WaveOutBuffer _mCurrentBuffer;
- private Task _mThread;
- private BufferFillEventHandler _mFillProc;
- private bool _mFinished;
-
- private bool _mPause;
-
- //public bool bPause
- //{
- // get { return m_Pause; }
- // set { m_Pause = value; }
- //}
- private readonly byte _mZero;
-
- private readonly WaveOutBase.WaveDelegate _mBufferProc = WaveOutBuffer.WaveOutProc;
-
- public static int DeviceCount => WaveOutBase.waveOutGetNumDevs();
-
- public WaveOut(int device, WaveFormat format, int bufferSize, int bufferCount, BufferFillEventHandler fillProc)
- {
- _mZero = format.wBitsPerSample == 8 ? (byte)128 : (byte)0;
- _mFillProc = fillProc;
- WaveOutHelper.Try(WaveOutBase.waveOutOpen(out _mWaveOut, device, format, _mBufferProc, 0,
- WaveOutBase.CallbackFunction));
- AllocateBuffers(bufferSize, bufferCount);
-
- _mThread = new Task(ThreadProc);
- _mThread.Start();
- }
-
- ~WaveOut()
- {
- Dispose();
- }
-
- public void Pause()
- {
- _mPause = true;
- WaveOutBase.waveOutPause(_mWaveOut);
- //WaveOutBase.waveOutReset(m_WaveOut);
- }
-
- public void Resume()
- {
- _mPause = false;
- WaveOutBase.waveOutRestart(_mWaveOut);
- }
-
- public void Dispose()
- {
- if (_mThread != null)
- try
- {
- _mPause = false;
- _mFinished = true;
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutReset(_mWaveOut);
-
- _mFillProc = null;
- FreeBuffers();
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutClose(_mWaveOut);
- }
- finally
- {
- _mThread = null;
- _mWaveOut = IntPtr.Zero;
- }
-
- GC.SuppressFinalize(this);
- }
-
- private void ThreadProc()
- {
- _mPause = false;
- while (!_mFinished)
- {
- // pause
- while (_mPause)
- {
- Thread.Sleep(10);
- }
-
- Advance();
- if (_mFillProc != null && !_mFinished)
- {
- _mFillProc(_mCurrentBuffer.Data, _mCurrentBuffer.Size);
- }
- else if (_mCurrentBuffer != null)
- {
- // zero out buffer
- var b = new byte[_mCurrentBuffer.Size];
- for (var i = 0; i < b.Length; i++)
- b[i] = _mZero;
- Marshal.Copy(b, 0, _mCurrentBuffer.Data, b.Length);
- }
-
- _mCurrentBuffer?.Play();
- }
-
- WaitForAllBuffers();
- }
-
- private void AllocateBuffers(int bufferSize, int bufferCount)
- {
- FreeBuffers();
- if (bufferCount <= 0) return;
- _mBuffers = new WaveOutBuffer(_mWaveOut, bufferSize);
- _mBuffers.Set(0);
- var prev = _mBuffers;
- try
- {
- for (var i = 1; i < bufferCount; i++)
- {
- var buf = new WaveOutBuffer(_mWaveOut, bufferSize);
- buf.Set(i);
- prev.NextBuffer = buf;
- prev = buf;
- }
- }
- finally
- {
- prev.NextBuffer = _mBuffers;
- }
- }
-
- private void FreeBuffers()
- {
- _mCurrentBuffer = null;
- if (_mBuffers == null) return;
- var first = _mBuffers;
- _mBuffers = null;
-
- var current = first;
- do
- {
- var next = current.NextBuffer;
- current.Dispose();
- current = next;
- } while (current != first);
- }
-
- private void Advance()
- {
- _mCurrentBuffer = _mCurrentBuffer == null ? _mBuffers : _mCurrentBuffer.NextBuffer;
- _mCurrentBuffer?.WaitFor();
- }
-
- private void WaitForAllBuffers()
- {
- var buf = _mBuffers;
- while (_mBuffers != null && buf.NextBuffer != _mBuffers)
- {
- buf.WaitFor();
- buf = buf.NextBuffer;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutBase.cs b/Correlator/Util/WaveOutBase.cs
deleted file mode 100644
index 4ce1442..0000000
--- a/Correlator/Util/WaveOutBase.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-
-namespace Correlator.Util
-{
- public enum WaveFormats
- {
- Pcm = 1,
- Float = 3
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class WaveFormat
- {
- public readonly short wFormatTag;
- public readonly short nChannels;
- public readonly int nSamplesPerSec;
- public readonly int nAvgBytesPerSec;
- public readonly short nBlockAlign;
- public readonly short wBitsPerSample;
- public readonly short cbSize;
-
- public WaveFormat(int rate, int bits, int channels)
- {
- wFormatTag = (short)WaveFormats.Pcm;
- nChannels = (short)channels;
- nSamplesPerSec = rate;
- wBitsPerSample = (short)bits;
- cbSize = 0;
-
- nBlockAlign = (short)(channels * (bits / 8));
- nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;
- }
- }
-
- internal static class WaveOutBase
- {
- public const int MmsyserrNoerror = 0; // no error
-
- public const int MmWomOpen = 0x3BB;
- public const int MmWomClose = 0x3BC;
- public const int MmWomDone = 0x3BD;
-
- public const int CallbackFunction = 0x00030000; // dwCallback is a FARPROC
-
- public const int TimeMs = 0x0001; // time in milliseconds
- public const int TimeSamples = 0x0002; // number of wave samples
- public const int TimeBytes = 0x0004; // current byte offset
-
- // callbacks
- public delegate void WaveDelegate(IntPtr hdrvr, int uMsg, int dwUser, ref WaveHdr wavhdr, int dwParam2);
-
- // structs
-
- [StructLayout(LayoutKind.Sequential)]
- public struct WaveHdr
- {
- public IntPtr lpData; // pointer to locked data buffer
- public int dwBufferLength; // length of data buffer
- public readonly int dwBytesRecorded; // used for input only
- public IntPtr dwUser; // for client's use+
- public readonly int dwFlags; // assorted flags (see defines)
- public readonly int dwLoops; // loop control counter
- public readonly IntPtr lpNext; // PWaveHdr, reserved for driver
- public readonly int reserved; // reserved for driver
- }
-
- private const string Mmdll = "winmm.dll";
-
- // native calls
- [DllImport(Mmdll)]
- public static extern int waveOutGetNumDevs();
-
- [DllImport(Mmdll)]
- public static extern int waveOutPrepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutUnprepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutWrite(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutOpen(out IntPtr hWaveOut, int uDeviceID, WaveFormat lpFormat,
- WaveDelegate dwCallback, int dwInstance, int dwFlags);
-
- [DllImport(Mmdll)]
- public static extern int waveOutReset(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutClose(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutPause(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutRestart(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetPosition(IntPtr hWaveOut, out int lpInfo, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutSetVolume(IntPtr hWaveOut, int dwVolume);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetVolume(IntPtr hWaveOut, out int dwVolume);
- }
-}
\ No newline at end of file
diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/DataService/AudioServiceImpl.cs b/Correlator/DataService/AudioServiceImpl.cs
index 12bfc7a..73c2f7e 100644
--- a/Correlator/DataService/AudioServiceImpl.cs
+++ b/Correlator/DataService/AudioServiceImpl.cs
@@ -1,4 +1,5 @@
using System;
+using Correlator.Util;
using NAudio.Wave;
namespace Correlator.DataService
@@ -18,10 +19,8 @@
_waveOut.Init(_lazyWaveProvider.Value);
_waveOut.Play();
- // var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
- // _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
- // var fileHeader = AudioHub.CreateWaveFileHeader(int.MaxValue, 7500, 16, 1);
- // _waveFileWriter.Write(fileHeader, 0, fileHeader.Length);
+ var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
+ _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
}
public void Write(byte[] pcm)
@@ -29,20 +28,20 @@
_lazyWaveProvider.Value.AddSamples(pcm, 0, pcm.Length);
//将pcm数据保存为wav格式文件
- // if (_waveFileWriter == null)
- // {
- // return;
- // }
- //
- // _waveFileWriter.Write(pcm, 0, pcm.Length);
+ if (_waveFileWriter == null)
+ {
+ return;
+ }
+
+ _waveFileWriter.Write(pcm, 0, pcm.Length);
}
public void Stop()
{
_waveOut.Stop();
- // _waveFileWriter.Dispose();
- // _waveFileWriter = null;
+ _waveFileWriter.Dispose();
+ _waveFileWriter = null;
}
}
}
\ No newline at end of file
diff --git a/Correlator/Util/PlayWav.cs b/Correlator/Util/PlayWav.cs
deleted file mode 100644
index a54ba0d..0000000
--- a/Correlator/Util/PlayWav.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace Correlator.Util
-{
- public class PlayWav
- {
- private WaveOut _wavPlayer;
-
- private WaveFormat _wavFormat;
-
- private bool _isPlaying;
- private WaveOutStream _waveOutStream;
-
- #region 单例
-
- private static readonly Lazy Lazy = new Lazy(() => new PlayWav());
-
- public static PlayWav Get => Lazy.Value;
-
- private PlayWav()
- {
- }
-
- #endregion
-
- public void InitWaveOut()
- {
- if (_isPlaying)
- {
- Stop();
- }
-
- try
- {
- //必须填入文件名,否则ws无法实例化
- var ws = new WaveOutStream(
- $"{DirectoryManager.GetAudioDir()}/Audio_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav"
- );
- _waveOutStream = ws;
- _waveOutStream.Position = 0;
- _wavFormat = ws.Format;
-
- _wavPlayer = new WaveOut(-1, _wavFormat, _wavFormat.nAvgBytesPerSec, 20, StreamBufferFiller);
- _isPlaying = true;
- }
- catch (Exception e)
- {
- "PlayWav".WriteLog(e.Message);
- }
- }
-
- public void Stop()
- {
- if (_wavPlayer == null) return;
-
- _wavPlayer.Dispose();
- _wavPlayer = null;
-
- //TODO 待优化。每次点击结束听音,但是While循环并没有立即结束,所以循环会直接报错
- if (_waveOutStream == null) return;
-
- _waveOutStream.Close();
- _waveOutStream = null;
- }
-
- public void Listen(byte[] bytesData)
- {
- var receiveBytesNum = bytesData.Length;
- if (_waveOutStream == null) return;
- lock (this)
- {
- _waveOutStream.Write(bytesData, 0, receiveBytesNum);
- }
- }
-
- private void StreamBufferFiller(IntPtr data, int size)
- {
- var buffer = new byte[size];
- if (_waveOutStream != null)
- {
- var pos = 0;
- while (pos < size)
- {
- var totalGet = size - pos;
- var got = _waveOutStream.Read(buffer, pos, totalGet);
- if (got <= 0)
- {
- Thread.Sleep(1000);
- }
-
- if (got < totalGet)
- {
- _waveOutStream.Position = 0; // loop if the file ends
- }
-
- pos += got;
- }
- }
- else
- {
- for (var i = 0; i < buffer.Length; i++)
- {
- buffer[i] = 0;
- }
- }
-
- Marshal.Copy(buffer, 0, data, size);
- }
-
- private void Dispose()
- {
- if (_wavPlayer == null) return;
- try
- {
- _wavPlayer.Dispose();
- }
- finally
- {
- _wavPlayer = null;
- }
- }
-
- ~PlayWav()
- {
- Dispose();
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOut.cs b/Correlator/Util/WaveOut.cs
deleted file mode 100644
index df51931..0000000
--- a/Correlator/Util/WaveOut.cs
+++ /dev/null
@@ -1,288 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Correlator.Util
-{
- internal static class WaveOutHelper
- {
- public static void Try(int err)
- {
- if (err != WaveOutBase.MmsyserrNoerror)
- throw new Exception(err.ToString());
- }
- }
-
- public delegate void BufferFillEventHandler(IntPtr data, int size);
-
- internal class WaveOutBuffer : IDisposable
- {
- public WaveOutBuffer NextBuffer;
-
- private readonly AutoResetEvent _mPlayEvent = new AutoResetEvent(false);
- private readonly IntPtr _mWaveOut;
-
- private WaveOutBase.WaveHdr _mHeader;
- private GCHandle _mHeaderHandle;
- private GCHandle _mHeaderDataHandle;
-
- private int _mark;
-
- private bool _mPlaying;
-
- internal static void WaveOutProc(IntPtr hdrvr, int uMsg, int dwUser, ref WaveOutBase.WaveHdr wavhdr,
- int dwParam2)
- {
- if (uMsg != WaveOutBase.MmWomDone) return;
- try
- {
- var h = (GCHandle)wavhdr.dwUser;
- var buf = (WaveOutBuffer)h.Target;
- buf.OnCompleted();
- }
- catch (Exception e)
- {
- "WaveOut".WriteLog(e.Message);
- }
- }
-
- public WaveOutBuffer(IntPtr waveOutHandle, int size)
- {
- _mWaveOut = waveOutHandle;
-
- _mHeaderHandle = GCHandle.Alloc(_mHeader, GCHandleType.Pinned);
- _mHeader.dwUser = (IntPtr)GCHandle.Alloc(this);
- var mHeaderData = new byte[size];
- _mHeaderDataHandle = GCHandle.Alloc(mHeaderData, GCHandleType.Pinned);
- _mHeader.lpData = _mHeaderDataHandle.AddrOfPinnedObject();
- _mHeader.dwBufferLength = size;
- WaveOutHelper.Try(WaveOutBase.waveOutPrepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)));
- }
-
- public void Set(int mark)
- {
- _mark = mark;
- }
-
- ~WaveOutBuffer()
- {
- Dispose();
- }
-
- public void Dispose()
- {
- if (_mHeader.lpData != IntPtr.Zero)
- {
- WaveOutBase.waveOutUnprepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader));
- _mHeaderHandle.Free();
- _mHeader.lpData = IntPtr.Zero;
- }
-
- _mPlayEvent.Close();
- if (_mHeaderDataHandle.IsAllocated)
- _mHeaderDataHandle.Free();
- GC.SuppressFinalize(this);
- }
-
- public int Size => _mHeader.dwBufferLength;
-
- public IntPtr Data => _mHeader.lpData;
-
- private void GetMemory(string title)
- {
- "WaveOut".WriteLog($"{title}: {_mPlaying}, {_mark}");
- }
-
- public bool Play()
- {
- lock (this)
- {
- GetMemory("Play");
- _mPlayEvent.Reset();
- _mPlaying = WaveOutBase.waveOutWrite(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)) ==
- WaveOutBase.MmsyserrNoerror;
- return _mPlaying;
- }
- }
-
- public void WaitFor()
- {
- GetMemory("WaitFor");
- if (_mPlaying)
- {
- _mPlaying = _mPlayEvent.WaitOne();
- }
- }
-
- private void OnCompleted()
- {
- GetMemory("OnCompleted");
- _mPlayEvent.Set();
- _mPlaying = false;
- }
- }
-
- public class WaveOut : IDisposable
- {
- private IntPtr _mWaveOut;
- private WaveOutBuffer _mBuffers; // linked list
- private WaveOutBuffer _mCurrentBuffer;
- private Task _mThread;
- private BufferFillEventHandler _mFillProc;
- private bool _mFinished;
-
- private bool _mPause;
-
- //public bool bPause
- //{
- // get { return m_Pause; }
- // set { m_Pause = value; }
- //}
- private readonly byte _mZero;
-
- private readonly WaveOutBase.WaveDelegate _mBufferProc = WaveOutBuffer.WaveOutProc;
-
- public static int DeviceCount => WaveOutBase.waveOutGetNumDevs();
-
- public WaveOut(int device, WaveFormat format, int bufferSize, int bufferCount, BufferFillEventHandler fillProc)
- {
- _mZero = format.wBitsPerSample == 8 ? (byte)128 : (byte)0;
- _mFillProc = fillProc;
- WaveOutHelper.Try(WaveOutBase.waveOutOpen(out _mWaveOut, device, format, _mBufferProc, 0,
- WaveOutBase.CallbackFunction));
- AllocateBuffers(bufferSize, bufferCount);
-
- _mThread = new Task(ThreadProc);
- _mThread.Start();
- }
-
- ~WaveOut()
- {
- Dispose();
- }
-
- public void Pause()
- {
- _mPause = true;
- WaveOutBase.waveOutPause(_mWaveOut);
- //WaveOutBase.waveOutReset(m_WaveOut);
- }
-
- public void Resume()
- {
- _mPause = false;
- WaveOutBase.waveOutRestart(_mWaveOut);
- }
-
- public void Dispose()
- {
- if (_mThread != null)
- try
- {
- _mPause = false;
- _mFinished = true;
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutReset(_mWaveOut);
-
- _mFillProc = null;
- FreeBuffers();
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutClose(_mWaveOut);
- }
- finally
- {
- _mThread = null;
- _mWaveOut = IntPtr.Zero;
- }
-
- GC.SuppressFinalize(this);
- }
-
- private void ThreadProc()
- {
- _mPause = false;
- while (!_mFinished)
- {
- // pause
- while (_mPause)
- {
- Thread.Sleep(10);
- }
-
- Advance();
- if (_mFillProc != null && !_mFinished)
- {
- _mFillProc(_mCurrentBuffer.Data, _mCurrentBuffer.Size);
- }
- else if (_mCurrentBuffer != null)
- {
- // zero out buffer
- var b = new byte[_mCurrentBuffer.Size];
- for (var i = 0; i < b.Length; i++)
- b[i] = _mZero;
- Marshal.Copy(b, 0, _mCurrentBuffer.Data, b.Length);
- }
-
- _mCurrentBuffer?.Play();
- }
-
- WaitForAllBuffers();
- }
-
- private void AllocateBuffers(int bufferSize, int bufferCount)
- {
- FreeBuffers();
- if (bufferCount <= 0) return;
- _mBuffers = new WaveOutBuffer(_mWaveOut, bufferSize);
- _mBuffers.Set(0);
- var prev = _mBuffers;
- try
- {
- for (var i = 1; i < bufferCount; i++)
- {
- var buf = new WaveOutBuffer(_mWaveOut, bufferSize);
- buf.Set(i);
- prev.NextBuffer = buf;
- prev = buf;
- }
- }
- finally
- {
- prev.NextBuffer = _mBuffers;
- }
- }
-
- private void FreeBuffers()
- {
- _mCurrentBuffer = null;
- if (_mBuffers == null) return;
- var first = _mBuffers;
- _mBuffers = null;
-
- var current = first;
- do
- {
- var next = current.NextBuffer;
- current.Dispose();
- current = next;
- } while (current != first);
- }
-
- private void Advance()
- {
- _mCurrentBuffer = _mCurrentBuffer == null ? _mBuffers : _mCurrentBuffer.NextBuffer;
- _mCurrentBuffer?.WaitFor();
- }
-
- private void WaitForAllBuffers()
- {
- var buf = _mBuffers;
- while (_mBuffers != null && buf.NextBuffer != _mBuffers)
- {
- buf.WaitFor();
- buf = buf.NextBuffer;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutBase.cs b/Correlator/Util/WaveOutBase.cs
deleted file mode 100644
index 4ce1442..0000000
--- a/Correlator/Util/WaveOutBase.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-
-namespace Correlator.Util
-{
- public enum WaveFormats
- {
- Pcm = 1,
- Float = 3
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class WaveFormat
- {
- public readonly short wFormatTag;
- public readonly short nChannels;
- public readonly int nSamplesPerSec;
- public readonly int nAvgBytesPerSec;
- public readonly short nBlockAlign;
- public readonly short wBitsPerSample;
- public readonly short cbSize;
-
- public WaveFormat(int rate, int bits, int channels)
- {
- wFormatTag = (short)WaveFormats.Pcm;
- nChannels = (short)channels;
- nSamplesPerSec = rate;
- wBitsPerSample = (short)bits;
- cbSize = 0;
-
- nBlockAlign = (short)(channels * (bits / 8));
- nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;
- }
- }
-
- internal static class WaveOutBase
- {
- public const int MmsyserrNoerror = 0; // no error
-
- public const int MmWomOpen = 0x3BB;
- public const int MmWomClose = 0x3BC;
- public const int MmWomDone = 0x3BD;
-
- public const int CallbackFunction = 0x00030000; // dwCallback is a FARPROC
-
- public const int TimeMs = 0x0001; // time in milliseconds
- public const int TimeSamples = 0x0002; // number of wave samples
- public const int TimeBytes = 0x0004; // current byte offset
-
- // callbacks
- public delegate void WaveDelegate(IntPtr hdrvr, int uMsg, int dwUser, ref WaveHdr wavhdr, int dwParam2);
-
- // structs
-
- [StructLayout(LayoutKind.Sequential)]
- public struct WaveHdr
- {
- public IntPtr lpData; // pointer to locked data buffer
- public int dwBufferLength; // length of data buffer
- public readonly int dwBytesRecorded; // used for input only
- public IntPtr dwUser; // for client's use+
- public readonly int dwFlags; // assorted flags (see defines)
- public readonly int dwLoops; // loop control counter
- public readonly IntPtr lpNext; // PWaveHdr, reserved for driver
- public readonly int reserved; // reserved for driver
- }
-
- private const string Mmdll = "winmm.dll";
-
- // native calls
- [DllImport(Mmdll)]
- public static extern int waveOutGetNumDevs();
-
- [DllImport(Mmdll)]
- public static extern int waveOutPrepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutUnprepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutWrite(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutOpen(out IntPtr hWaveOut, int uDeviceID, WaveFormat lpFormat,
- WaveDelegate dwCallback, int dwInstance, int dwFlags);
-
- [DllImport(Mmdll)]
- public static extern int waveOutReset(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutClose(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutPause(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutRestart(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetPosition(IntPtr hWaveOut, out int lpInfo, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutSetVolume(IntPtr hWaveOut, int dwVolume);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetVolume(IntPtr hWaveOut, out int dwVolume);
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutStream.cs b/Correlator/Util/WaveOutStream.cs
deleted file mode 100644
index 497f779..0000000
--- a/Correlator/Util/WaveOutStream.cs
+++ /dev/null
@@ -1,159 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-
-namespace Correlator.Util
-{
- public class WaveOutStream : Stream, IDisposable
- {
- private readonly Stream _mStream;
- private const int BufferSize = 7500 * 3 * 3600; //10 * 1024 *1024;
- private readonly byte[] _streamBuffer = new byte[BufferSize];
- private int _head;
- private int _tail;
-
- public WaveFormat Format { get; set; }
-
- private string ReadChunk(BinaryReader reader)
- {
- var ch = new byte[4];
- reader.Read(ch, 0, ch.Length);
- return Encoding.ASCII.GetString(ch);
- }
-
- public WaveOutStream(string fileName) : this(new FileStream(fileName, FileMode.OpenOrCreate))
- {
- }
-
- private WaveOutStream(Stream s)
- {
- _mStream = s;
- Format = new WaveFormat(7500, 24, 1); // initialize to any format
- }
-
- ~WaveOutStream()
- {
- Dispose();
- }
-
- public new void Dispose()
- {
- _mStream?.Close();
- GC.SuppressFinalize(this);
- }
-
- public override bool CanRead => true;
-
- public override bool CanSeek => true;
-
- public override bool CanWrite => false;
-
- public override long Length => 0;
-
- public override long Position
- {
- get => _mStream.Position;
- set => Seek(value, SeekOrigin.Begin);
- }
-
- public override void Close()
- {
- Dispose();
- }
-
- public override void Flush()
- {
- }
-
- public override void SetLength(long len)
- {
- throw new InvalidOperationException();
- }
-
- public override long Seek(long pos, SeekOrigin o)
- {
- switch (o)
- {
- case SeekOrigin.Begin:
- _mStream.Position = pos;
- break;
- case SeekOrigin.Current:
- _mStream.Seek(pos, SeekOrigin.Current);
- break;
- case SeekOrigin.End:
- _mStream.Position = pos;
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(o), o, null);
- }
-
- return Position;
- }
- //public override int Read(byte[] buf, int ofs, int count)
- //{
- // int toread = (int)Math.Min(count, m_Length - Position);
- // return m_Stream.Read(buf, ofs, toread);
- //}
- //public override void Write(byte[] buf, int ofs, int count)
- //{
- // throw new InvalidOperationException();
- //}
-
- // add for socket
- public override int Read(byte[] buf, int ofs, int count)
- {
- lock (this)
- {
- var leftSize = (BufferSize + _tail - _head) % BufferSize;
- if (leftSize < count)
- {
- // Console.WriteLine("left_size: {0}", left_size);
- return 0;
- }
-
- var tailSize = BufferSize - _head;
- var headSize = count - tailSize;
- if (tailSize < count)
- {
- Array.Copy(_streamBuffer, _head, buf, ofs, tailSize);
- Array.Copy(_streamBuffer, 0, buf, ofs + tailSize - 1, headSize);
- }
- else
- {
- Array.Copy(_streamBuffer, _head, buf, ofs, count);
- }
-
- _head = (_head + count) % BufferSize;
- }
-
- return count;
- }
-
-
- public override void Write(byte[] buf, int ofs, int count)
- {
- lock (this)
- {
- var emptySize = BufferSize - 1 - (BufferSize + _tail - _head) % BufferSize;
- if (emptySize < count)
- {
- return;
- }
-
- var tailSize = BufferSize - _tail - 1;
- var headSize = count - tailSize;
- if (tailSize < count)
- {
- Array.Copy(buf, ofs, _streamBuffer, _tail, tailSize);
- Array.Copy(buf, ofs + tailSize - 1, _streamBuffer, 0, headSize);
- }
- else
- {
- Array.Copy(buf, ofs, _streamBuffer, _tail, count);
- }
-
- _tail = (_tail + count) % BufferSize;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/DataService/AudioServiceImpl.cs b/Correlator/DataService/AudioServiceImpl.cs
index 12bfc7a..73c2f7e 100644
--- a/Correlator/DataService/AudioServiceImpl.cs
+++ b/Correlator/DataService/AudioServiceImpl.cs
@@ -1,4 +1,5 @@
using System;
+using Correlator.Util;
using NAudio.Wave;
namespace Correlator.DataService
@@ -18,10 +19,8 @@
_waveOut.Init(_lazyWaveProvider.Value);
_waveOut.Play();
- // var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
- // _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
- // var fileHeader = AudioHub.CreateWaveFileHeader(int.MaxValue, 7500, 16, 1);
- // _waveFileWriter.Write(fileHeader, 0, fileHeader.Length);
+ var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
+ _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
}
public void Write(byte[] pcm)
@@ -29,20 +28,20 @@
_lazyWaveProvider.Value.AddSamples(pcm, 0, pcm.Length);
//将pcm数据保存为wav格式文件
- // if (_waveFileWriter == null)
- // {
- // return;
- // }
- //
- // _waveFileWriter.Write(pcm, 0, pcm.Length);
+ if (_waveFileWriter == null)
+ {
+ return;
+ }
+
+ _waveFileWriter.Write(pcm, 0, pcm.Length);
}
public void Stop()
{
_waveOut.Stop();
- // _waveFileWriter.Dispose();
- // _waveFileWriter = null;
+ _waveFileWriter.Dispose();
+ _waveFileWriter = null;
}
}
}
\ No newline at end of file
diff --git a/Correlator/Util/PlayWav.cs b/Correlator/Util/PlayWav.cs
deleted file mode 100644
index a54ba0d..0000000
--- a/Correlator/Util/PlayWav.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace Correlator.Util
-{
- public class PlayWav
- {
- private WaveOut _wavPlayer;
-
- private WaveFormat _wavFormat;
-
- private bool _isPlaying;
- private WaveOutStream _waveOutStream;
-
- #region 单例
-
- private static readonly Lazy Lazy = new Lazy(() => new PlayWav());
-
- public static PlayWav Get => Lazy.Value;
-
- private PlayWav()
- {
- }
-
- #endregion
-
- public void InitWaveOut()
- {
- if (_isPlaying)
- {
- Stop();
- }
-
- try
- {
- //必须填入文件名,否则ws无法实例化
- var ws = new WaveOutStream(
- $"{DirectoryManager.GetAudioDir()}/Audio_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav"
- );
- _waveOutStream = ws;
- _waveOutStream.Position = 0;
- _wavFormat = ws.Format;
-
- _wavPlayer = new WaveOut(-1, _wavFormat, _wavFormat.nAvgBytesPerSec, 20, StreamBufferFiller);
- _isPlaying = true;
- }
- catch (Exception e)
- {
- "PlayWav".WriteLog(e.Message);
- }
- }
-
- public void Stop()
- {
- if (_wavPlayer == null) return;
-
- _wavPlayer.Dispose();
- _wavPlayer = null;
-
- //TODO 待优化。每次点击结束听音,但是While循环并没有立即结束,所以循环会直接报错
- if (_waveOutStream == null) return;
-
- _waveOutStream.Close();
- _waveOutStream = null;
- }
-
- public void Listen(byte[] bytesData)
- {
- var receiveBytesNum = bytesData.Length;
- if (_waveOutStream == null) return;
- lock (this)
- {
- _waveOutStream.Write(bytesData, 0, receiveBytesNum);
- }
- }
-
- private void StreamBufferFiller(IntPtr data, int size)
- {
- var buffer = new byte[size];
- if (_waveOutStream != null)
- {
- var pos = 0;
- while (pos < size)
- {
- var totalGet = size - pos;
- var got = _waveOutStream.Read(buffer, pos, totalGet);
- if (got <= 0)
- {
- Thread.Sleep(1000);
- }
-
- if (got < totalGet)
- {
- _waveOutStream.Position = 0; // loop if the file ends
- }
-
- pos += got;
- }
- }
- else
- {
- for (var i = 0; i < buffer.Length; i++)
- {
- buffer[i] = 0;
- }
- }
-
- Marshal.Copy(buffer, 0, data, size);
- }
-
- private void Dispose()
- {
- if (_wavPlayer == null) return;
- try
- {
- _wavPlayer.Dispose();
- }
- finally
- {
- _wavPlayer = null;
- }
- }
-
- ~PlayWav()
- {
- Dispose();
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOut.cs b/Correlator/Util/WaveOut.cs
deleted file mode 100644
index df51931..0000000
--- a/Correlator/Util/WaveOut.cs
+++ /dev/null
@@ -1,288 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Correlator.Util
-{
- internal static class WaveOutHelper
- {
- public static void Try(int err)
- {
- if (err != WaveOutBase.MmsyserrNoerror)
- throw new Exception(err.ToString());
- }
- }
-
- public delegate void BufferFillEventHandler(IntPtr data, int size);
-
- internal class WaveOutBuffer : IDisposable
- {
- public WaveOutBuffer NextBuffer;
-
- private readonly AutoResetEvent _mPlayEvent = new AutoResetEvent(false);
- private readonly IntPtr _mWaveOut;
-
- private WaveOutBase.WaveHdr _mHeader;
- private GCHandle _mHeaderHandle;
- private GCHandle _mHeaderDataHandle;
-
- private int _mark;
-
- private bool _mPlaying;
-
- internal static void WaveOutProc(IntPtr hdrvr, int uMsg, int dwUser, ref WaveOutBase.WaveHdr wavhdr,
- int dwParam2)
- {
- if (uMsg != WaveOutBase.MmWomDone) return;
- try
- {
- var h = (GCHandle)wavhdr.dwUser;
- var buf = (WaveOutBuffer)h.Target;
- buf.OnCompleted();
- }
- catch (Exception e)
- {
- "WaveOut".WriteLog(e.Message);
- }
- }
-
- public WaveOutBuffer(IntPtr waveOutHandle, int size)
- {
- _mWaveOut = waveOutHandle;
-
- _mHeaderHandle = GCHandle.Alloc(_mHeader, GCHandleType.Pinned);
- _mHeader.dwUser = (IntPtr)GCHandle.Alloc(this);
- var mHeaderData = new byte[size];
- _mHeaderDataHandle = GCHandle.Alloc(mHeaderData, GCHandleType.Pinned);
- _mHeader.lpData = _mHeaderDataHandle.AddrOfPinnedObject();
- _mHeader.dwBufferLength = size;
- WaveOutHelper.Try(WaveOutBase.waveOutPrepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)));
- }
-
- public void Set(int mark)
- {
- _mark = mark;
- }
-
- ~WaveOutBuffer()
- {
- Dispose();
- }
-
- public void Dispose()
- {
- if (_mHeader.lpData != IntPtr.Zero)
- {
- WaveOutBase.waveOutUnprepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader));
- _mHeaderHandle.Free();
- _mHeader.lpData = IntPtr.Zero;
- }
-
- _mPlayEvent.Close();
- if (_mHeaderDataHandle.IsAllocated)
- _mHeaderDataHandle.Free();
- GC.SuppressFinalize(this);
- }
-
- public int Size => _mHeader.dwBufferLength;
-
- public IntPtr Data => _mHeader.lpData;
-
- private void GetMemory(string title)
- {
- "WaveOut".WriteLog($"{title}: {_mPlaying}, {_mark}");
- }
-
- public bool Play()
- {
- lock (this)
- {
- GetMemory("Play");
- _mPlayEvent.Reset();
- _mPlaying = WaveOutBase.waveOutWrite(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)) ==
- WaveOutBase.MmsyserrNoerror;
- return _mPlaying;
- }
- }
-
- public void WaitFor()
- {
- GetMemory("WaitFor");
- if (_mPlaying)
- {
- _mPlaying = _mPlayEvent.WaitOne();
- }
- }
-
- private void OnCompleted()
- {
- GetMemory("OnCompleted");
- _mPlayEvent.Set();
- _mPlaying = false;
- }
- }
-
- public class WaveOut : IDisposable
- {
- private IntPtr _mWaveOut;
- private WaveOutBuffer _mBuffers; // linked list
- private WaveOutBuffer _mCurrentBuffer;
- private Task _mThread;
- private BufferFillEventHandler _mFillProc;
- private bool _mFinished;
-
- private bool _mPause;
-
- //public bool bPause
- //{
- // get { return m_Pause; }
- // set { m_Pause = value; }
- //}
- private readonly byte _mZero;
-
- private readonly WaveOutBase.WaveDelegate _mBufferProc = WaveOutBuffer.WaveOutProc;
-
- public static int DeviceCount => WaveOutBase.waveOutGetNumDevs();
-
- public WaveOut(int device, WaveFormat format, int bufferSize, int bufferCount, BufferFillEventHandler fillProc)
- {
- _mZero = format.wBitsPerSample == 8 ? (byte)128 : (byte)0;
- _mFillProc = fillProc;
- WaveOutHelper.Try(WaveOutBase.waveOutOpen(out _mWaveOut, device, format, _mBufferProc, 0,
- WaveOutBase.CallbackFunction));
- AllocateBuffers(bufferSize, bufferCount);
-
- _mThread = new Task(ThreadProc);
- _mThread.Start();
- }
-
- ~WaveOut()
- {
- Dispose();
- }
-
- public void Pause()
- {
- _mPause = true;
- WaveOutBase.waveOutPause(_mWaveOut);
- //WaveOutBase.waveOutReset(m_WaveOut);
- }
-
- public void Resume()
- {
- _mPause = false;
- WaveOutBase.waveOutRestart(_mWaveOut);
- }
-
- public void Dispose()
- {
- if (_mThread != null)
- try
- {
- _mPause = false;
- _mFinished = true;
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutReset(_mWaveOut);
-
- _mFillProc = null;
- FreeBuffers();
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutClose(_mWaveOut);
- }
- finally
- {
- _mThread = null;
- _mWaveOut = IntPtr.Zero;
- }
-
- GC.SuppressFinalize(this);
- }
-
- private void ThreadProc()
- {
- _mPause = false;
- while (!_mFinished)
- {
- // pause
- while (_mPause)
- {
- Thread.Sleep(10);
- }
-
- Advance();
- if (_mFillProc != null && !_mFinished)
- {
- _mFillProc(_mCurrentBuffer.Data, _mCurrentBuffer.Size);
- }
- else if (_mCurrentBuffer != null)
- {
- // zero out buffer
- var b = new byte[_mCurrentBuffer.Size];
- for (var i = 0; i < b.Length; i++)
- b[i] = _mZero;
- Marshal.Copy(b, 0, _mCurrentBuffer.Data, b.Length);
- }
-
- _mCurrentBuffer?.Play();
- }
-
- WaitForAllBuffers();
- }
-
- private void AllocateBuffers(int bufferSize, int bufferCount)
- {
- FreeBuffers();
- if (bufferCount <= 0) return;
- _mBuffers = new WaveOutBuffer(_mWaveOut, bufferSize);
- _mBuffers.Set(0);
- var prev = _mBuffers;
- try
- {
- for (var i = 1; i < bufferCount; i++)
- {
- var buf = new WaveOutBuffer(_mWaveOut, bufferSize);
- buf.Set(i);
- prev.NextBuffer = buf;
- prev = buf;
- }
- }
- finally
- {
- prev.NextBuffer = _mBuffers;
- }
- }
-
- private void FreeBuffers()
- {
- _mCurrentBuffer = null;
- if (_mBuffers == null) return;
- var first = _mBuffers;
- _mBuffers = null;
-
- var current = first;
- do
- {
- var next = current.NextBuffer;
- current.Dispose();
- current = next;
- } while (current != first);
- }
-
- private void Advance()
- {
- _mCurrentBuffer = _mCurrentBuffer == null ? _mBuffers : _mCurrentBuffer.NextBuffer;
- _mCurrentBuffer?.WaitFor();
- }
-
- private void WaitForAllBuffers()
- {
- var buf = _mBuffers;
- while (_mBuffers != null && buf.NextBuffer != _mBuffers)
- {
- buf.WaitFor();
- buf = buf.NextBuffer;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutBase.cs b/Correlator/Util/WaveOutBase.cs
deleted file mode 100644
index 4ce1442..0000000
--- a/Correlator/Util/WaveOutBase.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-
-namespace Correlator.Util
-{
- public enum WaveFormats
- {
- Pcm = 1,
- Float = 3
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class WaveFormat
- {
- public readonly short wFormatTag;
- public readonly short nChannels;
- public readonly int nSamplesPerSec;
- public readonly int nAvgBytesPerSec;
- public readonly short nBlockAlign;
- public readonly short wBitsPerSample;
- public readonly short cbSize;
-
- public WaveFormat(int rate, int bits, int channels)
- {
- wFormatTag = (short)WaveFormats.Pcm;
- nChannels = (short)channels;
- nSamplesPerSec = rate;
- wBitsPerSample = (short)bits;
- cbSize = 0;
-
- nBlockAlign = (short)(channels * (bits / 8));
- nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;
- }
- }
-
- internal static class WaveOutBase
- {
- public const int MmsyserrNoerror = 0; // no error
-
- public const int MmWomOpen = 0x3BB;
- public const int MmWomClose = 0x3BC;
- public const int MmWomDone = 0x3BD;
-
- public const int CallbackFunction = 0x00030000; // dwCallback is a FARPROC
-
- public const int TimeMs = 0x0001; // time in milliseconds
- public const int TimeSamples = 0x0002; // number of wave samples
- public const int TimeBytes = 0x0004; // current byte offset
-
- // callbacks
- public delegate void WaveDelegate(IntPtr hdrvr, int uMsg, int dwUser, ref WaveHdr wavhdr, int dwParam2);
-
- // structs
-
- [StructLayout(LayoutKind.Sequential)]
- public struct WaveHdr
- {
- public IntPtr lpData; // pointer to locked data buffer
- public int dwBufferLength; // length of data buffer
- public readonly int dwBytesRecorded; // used for input only
- public IntPtr dwUser; // for client's use+
- public readonly int dwFlags; // assorted flags (see defines)
- public readonly int dwLoops; // loop control counter
- public readonly IntPtr lpNext; // PWaveHdr, reserved for driver
- public readonly int reserved; // reserved for driver
- }
-
- private const string Mmdll = "winmm.dll";
-
- // native calls
- [DllImport(Mmdll)]
- public static extern int waveOutGetNumDevs();
-
- [DllImport(Mmdll)]
- public static extern int waveOutPrepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutUnprepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutWrite(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutOpen(out IntPtr hWaveOut, int uDeviceID, WaveFormat lpFormat,
- WaveDelegate dwCallback, int dwInstance, int dwFlags);
-
- [DllImport(Mmdll)]
- public static extern int waveOutReset(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutClose(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutPause(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutRestart(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetPosition(IntPtr hWaveOut, out int lpInfo, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutSetVolume(IntPtr hWaveOut, int dwVolume);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetVolume(IntPtr hWaveOut, out int dwVolume);
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutStream.cs b/Correlator/Util/WaveOutStream.cs
deleted file mode 100644
index 497f779..0000000
--- a/Correlator/Util/WaveOutStream.cs
+++ /dev/null
@@ -1,159 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-
-namespace Correlator.Util
-{
- public class WaveOutStream : Stream, IDisposable
- {
- private readonly Stream _mStream;
- private const int BufferSize = 7500 * 3 * 3600; //10 * 1024 *1024;
- private readonly byte[] _streamBuffer = new byte[BufferSize];
- private int _head;
- private int _tail;
-
- public WaveFormat Format { get; set; }
-
- private string ReadChunk(BinaryReader reader)
- {
- var ch = new byte[4];
- reader.Read(ch, 0, ch.Length);
- return Encoding.ASCII.GetString(ch);
- }
-
- public WaveOutStream(string fileName) : this(new FileStream(fileName, FileMode.OpenOrCreate))
- {
- }
-
- private WaveOutStream(Stream s)
- {
- _mStream = s;
- Format = new WaveFormat(7500, 24, 1); // initialize to any format
- }
-
- ~WaveOutStream()
- {
- Dispose();
- }
-
- public new void Dispose()
- {
- _mStream?.Close();
- GC.SuppressFinalize(this);
- }
-
- public override bool CanRead => true;
-
- public override bool CanSeek => true;
-
- public override bool CanWrite => false;
-
- public override long Length => 0;
-
- public override long Position
- {
- get => _mStream.Position;
- set => Seek(value, SeekOrigin.Begin);
- }
-
- public override void Close()
- {
- Dispose();
- }
-
- public override void Flush()
- {
- }
-
- public override void SetLength(long len)
- {
- throw new InvalidOperationException();
- }
-
- public override long Seek(long pos, SeekOrigin o)
- {
- switch (o)
- {
- case SeekOrigin.Begin:
- _mStream.Position = pos;
- break;
- case SeekOrigin.Current:
- _mStream.Seek(pos, SeekOrigin.Current);
- break;
- case SeekOrigin.End:
- _mStream.Position = pos;
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(o), o, null);
- }
-
- return Position;
- }
- //public override int Read(byte[] buf, int ofs, int count)
- //{
- // int toread = (int)Math.Min(count, m_Length - Position);
- // return m_Stream.Read(buf, ofs, toread);
- //}
- //public override void Write(byte[] buf, int ofs, int count)
- //{
- // throw new InvalidOperationException();
- //}
-
- // add for socket
- public override int Read(byte[] buf, int ofs, int count)
- {
- lock (this)
- {
- var leftSize = (BufferSize + _tail - _head) % BufferSize;
- if (leftSize < count)
- {
- // Console.WriteLine("left_size: {0}", left_size);
- return 0;
- }
-
- var tailSize = BufferSize - _head;
- var headSize = count - tailSize;
- if (tailSize < count)
- {
- Array.Copy(_streamBuffer, _head, buf, ofs, tailSize);
- Array.Copy(_streamBuffer, 0, buf, ofs + tailSize - 1, headSize);
- }
- else
- {
- Array.Copy(_streamBuffer, _head, buf, ofs, count);
- }
-
- _head = (_head + count) % BufferSize;
- }
-
- return count;
- }
-
-
- public override void Write(byte[] buf, int ofs, int count)
- {
- lock (this)
- {
- var emptySize = BufferSize - 1 - (BufferSize + _tail - _head) % BufferSize;
- if (emptySize < count)
- {
- return;
- }
-
- var tailSize = BufferSize - _tail - 1;
- var headSize = count - tailSize;
- if (tailSize < count)
- {
- Array.Copy(buf, ofs, _streamBuffer, _tail, tailSize);
- Array.Copy(buf, ofs + tailSize - 1, _streamBuffer, 0, headSize);
- }
- else
- {
- Array.Copy(buf, ofs, _streamBuffer, _tail, count);
- }
-
- _tail = (_tail + count) % BufferSize;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/ViewModels/AuditionViewModel.cs b/Correlator/ViewModels/AuditionViewModel.cs
index 19c2ae8..74376fa 100644
--- a/Correlator/ViewModels/AuditionViewModel.cs
+++ b/Correlator/ViewModels/AuditionViewModel.cs
@@ -1,6 +1,7 @@
using System;
using System.Runtime.InteropServices;
using Correlator.DataService;
+using Correlator.Events;
using Correlator.SensorHubTag;
using Correlator.Util;
using NAudio.CoreAudioApi;
@@ -81,30 +82,30 @@
BlueSensorMuteCommand = new DelegateCommand(SetCurrentMicVolume);
//音频监听
- // LazyWaveIn.Value.DataAvailable += delegate(object sender, WaveInEventArgs args)
- // {
- // _isStartRecording = true;
- //
- // var buffer = args.Buffer;
- //
- // var sts = new float[buffer.Length / 2];
- // var outIndex = 0;
- // for (var i = 0; i < buffer.Length; i += 2)
- // {
- // sts[outIndex++] = BitConverter.ToInt16(buffer, i) / 32768f;
- // }
- //
- // if (FlowStatus.CurrentListenSoundDevCode == DevCode.Dev1)
- // {
- // eventAggregator.GetEvent().Publish(sts);
- // }
- // else
- // {
- // eventAggregator.GetEvent().Publish(sts);
- // }
- // };
- //
- // LazyWaveIn.Value.RecordingStopped += delegate { _isStartRecording = false; };
+ LazyWaveIn.Value.DataAvailable += delegate(object sender, WaveInEventArgs args)
+ {
+ _isStartRecording = true;
+
+ var buffer = args.Buffer;
+
+ var sts = new float[buffer.Length / 2];
+ var outIndex = 0;
+ for (var i = 0; i < buffer.Length; i += 2)
+ {
+ sts[outIndex++] = BitConverter.ToInt16(buffer, i) / 32768f;
+ }
+
+ if (FlowStatus.CurrentListenSoundDevCode == DevCode.Dev1)
+ {
+ eventAggregator.GetEvent().Publish(sts);
+ }
+ else
+ {
+ eventAggregator.GetEvent().Publish(sts);
+ }
+ };
+
+ LazyWaveIn.Value.RecordingStopped += delegate { _isStartRecording = false; };
}
///
diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/DataService/AudioServiceImpl.cs b/Correlator/DataService/AudioServiceImpl.cs
index 12bfc7a..73c2f7e 100644
--- a/Correlator/DataService/AudioServiceImpl.cs
+++ b/Correlator/DataService/AudioServiceImpl.cs
@@ -1,4 +1,5 @@
using System;
+using Correlator.Util;
using NAudio.Wave;
namespace Correlator.DataService
@@ -18,10 +19,8 @@
_waveOut.Init(_lazyWaveProvider.Value);
_waveOut.Play();
- // var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
- // _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
- // var fileHeader = AudioHub.CreateWaveFileHeader(int.MaxValue, 7500, 16, 1);
- // _waveFileWriter.Write(fileHeader, 0, fileHeader.Length);
+ var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
+ _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
}
public void Write(byte[] pcm)
@@ -29,20 +28,20 @@
_lazyWaveProvider.Value.AddSamples(pcm, 0, pcm.Length);
//将pcm数据保存为wav格式文件
- // if (_waveFileWriter == null)
- // {
- // return;
- // }
- //
- // _waveFileWriter.Write(pcm, 0, pcm.Length);
+ if (_waveFileWriter == null)
+ {
+ return;
+ }
+
+ _waveFileWriter.Write(pcm, 0, pcm.Length);
}
public void Stop()
{
_waveOut.Stop();
- // _waveFileWriter.Dispose();
- // _waveFileWriter = null;
+ _waveFileWriter.Dispose();
+ _waveFileWriter = null;
}
}
}
\ No newline at end of file
diff --git a/Correlator/Util/PlayWav.cs b/Correlator/Util/PlayWav.cs
deleted file mode 100644
index a54ba0d..0000000
--- a/Correlator/Util/PlayWav.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace Correlator.Util
-{
- public class PlayWav
- {
- private WaveOut _wavPlayer;
-
- private WaveFormat _wavFormat;
-
- private bool _isPlaying;
- private WaveOutStream _waveOutStream;
-
- #region 单例
-
- private static readonly Lazy Lazy = new Lazy(() => new PlayWav());
-
- public static PlayWav Get => Lazy.Value;
-
- private PlayWav()
- {
- }
-
- #endregion
-
- public void InitWaveOut()
- {
- if (_isPlaying)
- {
- Stop();
- }
-
- try
- {
- //必须填入文件名,否则ws无法实例化
- var ws = new WaveOutStream(
- $"{DirectoryManager.GetAudioDir()}/Audio_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav"
- );
- _waveOutStream = ws;
- _waveOutStream.Position = 0;
- _wavFormat = ws.Format;
-
- _wavPlayer = new WaveOut(-1, _wavFormat, _wavFormat.nAvgBytesPerSec, 20, StreamBufferFiller);
- _isPlaying = true;
- }
- catch (Exception e)
- {
- "PlayWav".WriteLog(e.Message);
- }
- }
-
- public void Stop()
- {
- if (_wavPlayer == null) return;
-
- _wavPlayer.Dispose();
- _wavPlayer = null;
-
- //TODO 待优化。每次点击结束听音,但是While循环并没有立即结束,所以循环会直接报错
- if (_waveOutStream == null) return;
-
- _waveOutStream.Close();
- _waveOutStream = null;
- }
-
- public void Listen(byte[] bytesData)
- {
- var receiveBytesNum = bytesData.Length;
- if (_waveOutStream == null) return;
- lock (this)
- {
- _waveOutStream.Write(bytesData, 0, receiveBytesNum);
- }
- }
-
- private void StreamBufferFiller(IntPtr data, int size)
- {
- var buffer = new byte[size];
- if (_waveOutStream != null)
- {
- var pos = 0;
- while (pos < size)
- {
- var totalGet = size - pos;
- var got = _waveOutStream.Read(buffer, pos, totalGet);
- if (got <= 0)
- {
- Thread.Sleep(1000);
- }
-
- if (got < totalGet)
- {
- _waveOutStream.Position = 0; // loop if the file ends
- }
-
- pos += got;
- }
- }
- else
- {
- for (var i = 0; i < buffer.Length; i++)
- {
- buffer[i] = 0;
- }
- }
-
- Marshal.Copy(buffer, 0, data, size);
- }
-
- private void Dispose()
- {
- if (_wavPlayer == null) return;
- try
- {
- _wavPlayer.Dispose();
- }
- finally
- {
- _wavPlayer = null;
- }
- }
-
- ~PlayWav()
- {
- Dispose();
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOut.cs b/Correlator/Util/WaveOut.cs
deleted file mode 100644
index df51931..0000000
--- a/Correlator/Util/WaveOut.cs
+++ /dev/null
@@ -1,288 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Correlator.Util
-{
- internal static class WaveOutHelper
- {
- public static void Try(int err)
- {
- if (err != WaveOutBase.MmsyserrNoerror)
- throw new Exception(err.ToString());
- }
- }
-
- public delegate void BufferFillEventHandler(IntPtr data, int size);
-
- internal class WaveOutBuffer : IDisposable
- {
- public WaveOutBuffer NextBuffer;
-
- private readonly AutoResetEvent _mPlayEvent = new AutoResetEvent(false);
- private readonly IntPtr _mWaveOut;
-
- private WaveOutBase.WaveHdr _mHeader;
- private GCHandle _mHeaderHandle;
- private GCHandle _mHeaderDataHandle;
-
- private int _mark;
-
- private bool _mPlaying;
-
- internal static void WaveOutProc(IntPtr hdrvr, int uMsg, int dwUser, ref WaveOutBase.WaveHdr wavhdr,
- int dwParam2)
- {
- if (uMsg != WaveOutBase.MmWomDone) return;
- try
- {
- var h = (GCHandle)wavhdr.dwUser;
- var buf = (WaveOutBuffer)h.Target;
- buf.OnCompleted();
- }
- catch (Exception e)
- {
- "WaveOut".WriteLog(e.Message);
- }
- }
-
- public WaveOutBuffer(IntPtr waveOutHandle, int size)
- {
- _mWaveOut = waveOutHandle;
-
- _mHeaderHandle = GCHandle.Alloc(_mHeader, GCHandleType.Pinned);
- _mHeader.dwUser = (IntPtr)GCHandle.Alloc(this);
- var mHeaderData = new byte[size];
- _mHeaderDataHandle = GCHandle.Alloc(mHeaderData, GCHandleType.Pinned);
- _mHeader.lpData = _mHeaderDataHandle.AddrOfPinnedObject();
- _mHeader.dwBufferLength = size;
- WaveOutHelper.Try(WaveOutBase.waveOutPrepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)));
- }
-
- public void Set(int mark)
- {
- _mark = mark;
- }
-
- ~WaveOutBuffer()
- {
- Dispose();
- }
-
- public void Dispose()
- {
- if (_mHeader.lpData != IntPtr.Zero)
- {
- WaveOutBase.waveOutUnprepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader));
- _mHeaderHandle.Free();
- _mHeader.lpData = IntPtr.Zero;
- }
-
- _mPlayEvent.Close();
- if (_mHeaderDataHandle.IsAllocated)
- _mHeaderDataHandle.Free();
- GC.SuppressFinalize(this);
- }
-
- public int Size => _mHeader.dwBufferLength;
-
- public IntPtr Data => _mHeader.lpData;
-
- private void GetMemory(string title)
- {
- "WaveOut".WriteLog($"{title}: {_mPlaying}, {_mark}");
- }
-
- public bool Play()
- {
- lock (this)
- {
- GetMemory("Play");
- _mPlayEvent.Reset();
- _mPlaying = WaveOutBase.waveOutWrite(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)) ==
- WaveOutBase.MmsyserrNoerror;
- return _mPlaying;
- }
- }
-
- public void WaitFor()
- {
- GetMemory("WaitFor");
- if (_mPlaying)
- {
- _mPlaying = _mPlayEvent.WaitOne();
- }
- }
-
- private void OnCompleted()
- {
- GetMemory("OnCompleted");
- _mPlayEvent.Set();
- _mPlaying = false;
- }
- }
-
- public class WaveOut : IDisposable
- {
- private IntPtr _mWaveOut;
- private WaveOutBuffer _mBuffers; // linked list
- private WaveOutBuffer _mCurrentBuffer;
- private Task _mThread;
- private BufferFillEventHandler _mFillProc;
- private bool _mFinished;
-
- private bool _mPause;
-
- //public bool bPause
- //{
- // get { return m_Pause; }
- // set { m_Pause = value; }
- //}
- private readonly byte _mZero;
-
- private readonly WaveOutBase.WaveDelegate _mBufferProc = WaveOutBuffer.WaveOutProc;
-
- public static int DeviceCount => WaveOutBase.waveOutGetNumDevs();
-
- public WaveOut(int device, WaveFormat format, int bufferSize, int bufferCount, BufferFillEventHandler fillProc)
- {
- _mZero = format.wBitsPerSample == 8 ? (byte)128 : (byte)0;
- _mFillProc = fillProc;
- WaveOutHelper.Try(WaveOutBase.waveOutOpen(out _mWaveOut, device, format, _mBufferProc, 0,
- WaveOutBase.CallbackFunction));
- AllocateBuffers(bufferSize, bufferCount);
-
- _mThread = new Task(ThreadProc);
- _mThread.Start();
- }
-
- ~WaveOut()
- {
- Dispose();
- }
-
- public void Pause()
- {
- _mPause = true;
- WaveOutBase.waveOutPause(_mWaveOut);
- //WaveOutBase.waveOutReset(m_WaveOut);
- }
-
- public void Resume()
- {
- _mPause = false;
- WaveOutBase.waveOutRestart(_mWaveOut);
- }
-
- public void Dispose()
- {
- if (_mThread != null)
- try
- {
- _mPause = false;
- _mFinished = true;
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutReset(_mWaveOut);
-
- _mFillProc = null;
- FreeBuffers();
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutClose(_mWaveOut);
- }
- finally
- {
- _mThread = null;
- _mWaveOut = IntPtr.Zero;
- }
-
- GC.SuppressFinalize(this);
- }
-
- private void ThreadProc()
- {
- _mPause = false;
- while (!_mFinished)
- {
- // pause
- while (_mPause)
- {
- Thread.Sleep(10);
- }
-
- Advance();
- if (_mFillProc != null && !_mFinished)
- {
- _mFillProc(_mCurrentBuffer.Data, _mCurrentBuffer.Size);
- }
- else if (_mCurrentBuffer != null)
- {
- // zero out buffer
- var b = new byte[_mCurrentBuffer.Size];
- for (var i = 0; i < b.Length; i++)
- b[i] = _mZero;
- Marshal.Copy(b, 0, _mCurrentBuffer.Data, b.Length);
- }
-
- _mCurrentBuffer?.Play();
- }
-
- WaitForAllBuffers();
- }
-
- private void AllocateBuffers(int bufferSize, int bufferCount)
- {
- FreeBuffers();
- if (bufferCount <= 0) return;
- _mBuffers = new WaveOutBuffer(_mWaveOut, bufferSize);
- _mBuffers.Set(0);
- var prev = _mBuffers;
- try
- {
- for (var i = 1; i < bufferCount; i++)
- {
- var buf = new WaveOutBuffer(_mWaveOut, bufferSize);
- buf.Set(i);
- prev.NextBuffer = buf;
- prev = buf;
- }
- }
- finally
- {
- prev.NextBuffer = _mBuffers;
- }
- }
-
- private void FreeBuffers()
- {
- _mCurrentBuffer = null;
- if (_mBuffers == null) return;
- var first = _mBuffers;
- _mBuffers = null;
-
- var current = first;
- do
- {
- var next = current.NextBuffer;
- current.Dispose();
- current = next;
- } while (current != first);
- }
-
- private void Advance()
- {
- _mCurrentBuffer = _mCurrentBuffer == null ? _mBuffers : _mCurrentBuffer.NextBuffer;
- _mCurrentBuffer?.WaitFor();
- }
-
- private void WaitForAllBuffers()
- {
- var buf = _mBuffers;
- while (_mBuffers != null && buf.NextBuffer != _mBuffers)
- {
- buf.WaitFor();
- buf = buf.NextBuffer;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutBase.cs b/Correlator/Util/WaveOutBase.cs
deleted file mode 100644
index 4ce1442..0000000
--- a/Correlator/Util/WaveOutBase.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-
-namespace Correlator.Util
-{
- public enum WaveFormats
- {
- Pcm = 1,
- Float = 3
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class WaveFormat
- {
- public readonly short wFormatTag;
- public readonly short nChannels;
- public readonly int nSamplesPerSec;
- public readonly int nAvgBytesPerSec;
- public readonly short nBlockAlign;
- public readonly short wBitsPerSample;
- public readonly short cbSize;
-
- public WaveFormat(int rate, int bits, int channels)
- {
- wFormatTag = (short)WaveFormats.Pcm;
- nChannels = (short)channels;
- nSamplesPerSec = rate;
- wBitsPerSample = (short)bits;
- cbSize = 0;
-
- nBlockAlign = (short)(channels * (bits / 8));
- nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;
- }
- }
-
- internal static class WaveOutBase
- {
- public const int MmsyserrNoerror = 0; // no error
-
- public const int MmWomOpen = 0x3BB;
- public const int MmWomClose = 0x3BC;
- public const int MmWomDone = 0x3BD;
-
- public const int CallbackFunction = 0x00030000; // dwCallback is a FARPROC
-
- public const int TimeMs = 0x0001; // time in milliseconds
- public const int TimeSamples = 0x0002; // number of wave samples
- public const int TimeBytes = 0x0004; // current byte offset
-
- // callbacks
- public delegate void WaveDelegate(IntPtr hdrvr, int uMsg, int dwUser, ref WaveHdr wavhdr, int dwParam2);
-
- // structs
-
- [StructLayout(LayoutKind.Sequential)]
- public struct WaveHdr
- {
- public IntPtr lpData; // pointer to locked data buffer
- public int dwBufferLength; // length of data buffer
- public readonly int dwBytesRecorded; // used for input only
- public IntPtr dwUser; // for client's use+
- public readonly int dwFlags; // assorted flags (see defines)
- public readonly int dwLoops; // loop control counter
- public readonly IntPtr lpNext; // PWaveHdr, reserved for driver
- public readonly int reserved; // reserved for driver
- }
-
- private const string Mmdll = "winmm.dll";
-
- // native calls
- [DllImport(Mmdll)]
- public static extern int waveOutGetNumDevs();
-
- [DllImport(Mmdll)]
- public static extern int waveOutPrepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutUnprepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutWrite(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutOpen(out IntPtr hWaveOut, int uDeviceID, WaveFormat lpFormat,
- WaveDelegate dwCallback, int dwInstance, int dwFlags);
-
- [DllImport(Mmdll)]
- public static extern int waveOutReset(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutClose(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutPause(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutRestart(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetPosition(IntPtr hWaveOut, out int lpInfo, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutSetVolume(IntPtr hWaveOut, int dwVolume);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetVolume(IntPtr hWaveOut, out int dwVolume);
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutStream.cs b/Correlator/Util/WaveOutStream.cs
deleted file mode 100644
index 497f779..0000000
--- a/Correlator/Util/WaveOutStream.cs
+++ /dev/null
@@ -1,159 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-
-namespace Correlator.Util
-{
- public class WaveOutStream : Stream, IDisposable
- {
- private readonly Stream _mStream;
- private const int BufferSize = 7500 * 3 * 3600; //10 * 1024 *1024;
- private readonly byte[] _streamBuffer = new byte[BufferSize];
- private int _head;
- private int _tail;
-
- public WaveFormat Format { get; set; }
-
- private string ReadChunk(BinaryReader reader)
- {
- var ch = new byte[4];
- reader.Read(ch, 0, ch.Length);
- return Encoding.ASCII.GetString(ch);
- }
-
- public WaveOutStream(string fileName) : this(new FileStream(fileName, FileMode.OpenOrCreate))
- {
- }
-
- private WaveOutStream(Stream s)
- {
- _mStream = s;
- Format = new WaveFormat(7500, 24, 1); // initialize to any format
- }
-
- ~WaveOutStream()
- {
- Dispose();
- }
-
- public new void Dispose()
- {
- _mStream?.Close();
- GC.SuppressFinalize(this);
- }
-
- public override bool CanRead => true;
-
- public override bool CanSeek => true;
-
- public override bool CanWrite => false;
-
- public override long Length => 0;
-
- public override long Position
- {
- get => _mStream.Position;
- set => Seek(value, SeekOrigin.Begin);
- }
-
- public override void Close()
- {
- Dispose();
- }
-
- public override void Flush()
- {
- }
-
- public override void SetLength(long len)
- {
- throw new InvalidOperationException();
- }
-
- public override long Seek(long pos, SeekOrigin o)
- {
- switch (o)
- {
- case SeekOrigin.Begin:
- _mStream.Position = pos;
- break;
- case SeekOrigin.Current:
- _mStream.Seek(pos, SeekOrigin.Current);
- break;
- case SeekOrigin.End:
- _mStream.Position = pos;
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(o), o, null);
- }
-
- return Position;
- }
- //public override int Read(byte[] buf, int ofs, int count)
- //{
- // int toread = (int)Math.Min(count, m_Length - Position);
- // return m_Stream.Read(buf, ofs, toread);
- //}
- //public override void Write(byte[] buf, int ofs, int count)
- //{
- // throw new InvalidOperationException();
- //}
-
- // add for socket
- public override int Read(byte[] buf, int ofs, int count)
- {
- lock (this)
- {
- var leftSize = (BufferSize + _tail - _head) % BufferSize;
- if (leftSize < count)
- {
- // Console.WriteLine("left_size: {0}", left_size);
- return 0;
- }
-
- var tailSize = BufferSize - _head;
- var headSize = count - tailSize;
- if (tailSize < count)
- {
- Array.Copy(_streamBuffer, _head, buf, ofs, tailSize);
- Array.Copy(_streamBuffer, 0, buf, ofs + tailSize - 1, headSize);
- }
- else
- {
- Array.Copy(_streamBuffer, _head, buf, ofs, count);
- }
-
- _head = (_head + count) % BufferSize;
- }
-
- return count;
- }
-
-
- public override void Write(byte[] buf, int ofs, int count)
- {
- lock (this)
- {
- var emptySize = BufferSize - 1 - (BufferSize + _tail - _head) % BufferSize;
- if (emptySize < count)
- {
- return;
- }
-
- var tailSize = BufferSize - _tail - 1;
- var headSize = count - tailSize;
- if (tailSize < count)
- {
- Array.Copy(buf, ofs, _streamBuffer, _tail, tailSize);
- Array.Copy(buf, ofs + tailSize - 1, _streamBuffer, 0, headSize);
- }
- else
- {
- Array.Copy(buf, ofs, _streamBuffer, _tail, count);
- }
-
- _tail = (_tail + count) % BufferSize;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/ViewModels/AuditionViewModel.cs b/Correlator/ViewModels/AuditionViewModel.cs
index 19c2ae8..74376fa 100644
--- a/Correlator/ViewModels/AuditionViewModel.cs
+++ b/Correlator/ViewModels/AuditionViewModel.cs
@@ -1,6 +1,7 @@
using System;
using System.Runtime.InteropServices;
using Correlator.DataService;
+using Correlator.Events;
using Correlator.SensorHubTag;
using Correlator.Util;
using NAudio.CoreAudioApi;
@@ -81,30 +82,30 @@
BlueSensorMuteCommand = new DelegateCommand(SetCurrentMicVolume);
//音频监听
- // LazyWaveIn.Value.DataAvailable += delegate(object sender, WaveInEventArgs args)
- // {
- // _isStartRecording = true;
- //
- // var buffer = args.Buffer;
- //
- // var sts = new float[buffer.Length / 2];
- // var outIndex = 0;
- // for (var i = 0; i < buffer.Length; i += 2)
- // {
- // sts[outIndex++] = BitConverter.ToInt16(buffer, i) / 32768f;
- // }
- //
- // if (FlowStatus.CurrentListenSoundDevCode == DevCode.Dev1)
- // {
- // eventAggregator.GetEvent().Publish(sts);
- // }
- // else
- // {
- // eventAggregator.GetEvent().Publish(sts);
- // }
- // };
- //
- // LazyWaveIn.Value.RecordingStopped += delegate { _isStartRecording = false; };
+ LazyWaveIn.Value.DataAvailable += delegate(object sender, WaveInEventArgs args)
+ {
+ _isStartRecording = true;
+
+ var buffer = args.Buffer;
+
+ var sts = new float[buffer.Length / 2];
+ var outIndex = 0;
+ for (var i = 0; i < buffer.Length; i += 2)
+ {
+ sts[outIndex++] = BitConverter.ToInt16(buffer, i) / 32768f;
+ }
+
+ if (FlowStatus.CurrentListenSoundDevCode == DevCode.Dev1)
+ {
+ eventAggregator.GetEvent().Publish(sts);
+ }
+ else
+ {
+ eventAggregator.GetEvent().Publish(sts);
+ }
+ };
+
+ LazyWaveIn.Value.RecordingStopped += delegate { _isStartRecording = false; };
}
///
diff --git a/Correlator/Views/AuditionView.xaml.cs b/Correlator/Views/AuditionView.xaml.cs
index 27cf9c2..9fca3f0 100644
--- a/Correlator/Views/AuditionView.xaml.cs
+++ b/Correlator/Views/AuditionView.xaml.cs
@@ -15,17 +15,16 @@
InitializeComponent();
var redSensorPlot = RedSensorScottPlotChart.Plot;
+ //去掉网格线
+ redSensorPlot.Grid(false);
//去掉四周坐标轴
- redSensorPlot.XAxis.IsVisible = false;
- redSensorPlot.XAxis2.IsVisible = false;
- redSensorPlot.YAxis.IsVisible = false;
- redSensorPlot.YAxis2.IsVisible = false;
+ redSensorPlot.Frameless();
var blueSensorPlot = BlueSensorScottPlotChart.Plot;
- blueSensorPlot.XAxis.IsVisible = false;
- blueSensorPlot.XAxis2.IsVisible = false;
- blueSensorPlot.YAxis.IsVisible = false;
- blueSensorPlot.YAxis2.IsVisible = false;
+ //去掉网格线
+ blueSensorPlot.Grid(false);
+ //去掉四周坐标轴
+ blueSensorPlot.Frameless();
eventAggregator.GetEvent().Subscribe(delegate(float[] floats)
{
@@ -34,16 +33,16 @@
{
RedSensorScottPlotChart.Plot.Clear();
RedSensorScottPlotChart.Refresh();
-
+
var xDoubles = new List();
var yDoubles = new List();
-
+
for (var i = 0; i < floats.Length; i++)
{
xDoubles.Add(i);
yDoubles.Add(floats[i]);
}
-
+
RedSensorScottPlotChart.Plot.AddSignalXY(xDoubles.ToArray(), yDoubles.ToArray(), Color.LimeGreen);
RedSensorScottPlotChart.Refresh();
}
@@ -51,16 +50,16 @@
{
BlueSensorScottPlotChart.Plot.Clear();
BlueSensorScottPlotChart.Refresh();
-
+
var xDoubles = new List();
var yDoubles = new List();
-
+
for (var i = 0; i < floats.Length; i++)
{
xDoubles.Add(i);
yDoubles.Add(floats[i]);
}
-
+
BlueSensorScottPlotChart.Plot.AddSignalXY(xDoubles.ToArray(), yDoubles.ToArray(), Color.LimeGreen);
BlueSensorScottPlotChart.Refresh();
}
diff --git a/Correlator/Correlator.csproj b/Correlator/Correlator.csproj
index 014fc50..a0c7d81 100644
--- a/Correlator/Correlator.csproj
+++ b/Correlator/Correlator.csproj
@@ -246,7 +246,6 @@
-
@@ -255,13 +254,9 @@
-
-
-
-
diff --git a/Correlator/DataService/AudioServiceImpl.cs b/Correlator/DataService/AudioServiceImpl.cs
index 12bfc7a..73c2f7e 100644
--- a/Correlator/DataService/AudioServiceImpl.cs
+++ b/Correlator/DataService/AudioServiceImpl.cs
@@ -1,4 +1,5 @@
using System;
+using Correlator.Util;
using NAudio.Wave;
namespace Correlator.DataService
@@ -18,10 +19,8 @@
_waveOut.Init(_lazyWaveProvider.Value);
_waveOut.Play();
- // var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
- // _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
- // var fileHeader = AudioHub.CreateWaveFileHeader(int.MaxValue, 7500, 16, 1);
- // _waveFileWriter.Write(fileHeader, 0, fileHeader.Length);
+ var fileName = $"{DirectoryManager.GetAudioDir()}/听音_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav";
+ _waveFileWriter = new WaveFileWriter(fileName, new WaveFormat(7500, 24, 1));
}
public void Write(byte[] pcm)
@@ -29,20 +28,20 @@
_lazyWaveProvider.Value.AddSamples(pcm, 0, pcm.Length);
//将pcm数据保存为wav格式文件
- // if (_waveFileWriter == null)
- // {
- // return;
- // }
- //
- // _waveFileWriter.Write(pcm, 0, pcm.Length);
+ if (_waveFileWriter == null)
+ {
+ return;
+ }
+
+ _waveFileWriter.Write(pcm, 0, pcm.Length);
}
public void Stop()
{
_waveOut.Stop();
- // _waveFileWriter.Dispose();
- // _waveFileWriter = null;
+ _waveFileWriter.Dispose();
+ _waveFileWriter = null;
}
}
}
\ No newline at end of file
diff --git a/Correlator/Util/PlayWav.cs b/Correlator/Util/PlayWav.cs
deleted file mode 100644
index a54ba0d..0000000
--- a/Correlator/Util/PlayWav.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace Correlator.Util
-{
- public class PlayWav
- {
- private WaveOut _wavPlayer;
-
- private WaveFormat _wavFormat;
-
- private bool _isPlaying;
- private WaveOutStream _waveOutStream;
-
- #region 单例
-
- private static readonly Lazy Lazy = new Lazy(() => new PlayWav());
-
- public static PlayWav Get => Lazy.Value;
-
- private PlayWav()
- {
- }
-
- #endregion
-
- public void InitWaveOut()
- {
- if (_isPlaying)
- {
- Stop();
- }
-
- try
- {
- //必须填入文件名,否则ws无法实例化
- var ws = new WaveOutStream(
- $"{DirectoryManager.GetAudioDir()}/Audio_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.wav"
- );
- _waveOutStream = ws;
- _waveOutStream.Position = 0;
- _wavFormat = ws.Format;
-
- _wavPlayer = new WaveOut(-1, _wavFormat, _wavFormat.nAvgBytesPerSec, 20, StreamBufferFiller);
- _isPlaying = true;
- }
- catch (Exception e)
- {
- "PlayWav".WriteLog(e.Message);
- }
- }
-
- public void Stop()
- {
- if (_wavPlayer == null) return;
-
- _wavPlayer.Dispose();
- _wavPlayer = null;
-
- //TODO 待优化。每次点击结束听音,但是While循环并没有立即结束,所以循环会直接报错
- if (_waveOutStream == null) return;
-
- _waveOutStream.Close();
- _waveOutStream = null;
- }
-
- public void Listen(byte[] bytesData)
- {
- var receiveBytesNum = bytesData.Length;
- if (_waveOutStream == null) return;
- lock (this)
- {
- _waveOutStream.Write(bytesData, 0, receiveBytesNum);
- }
- }
-
- private void StreamBufferFiller(IntPtr data, int size)
- {
- var buffer = new byte[size];
- if (_waveOutStream != null)
- {
- var pos = 0;
- while (pos < size)
- {
- var totalGet = size - pos;
- var got = _waveOutStream.Read(buffer, pos, totalGet);
- if (got <= 0)
- {
- Thread.Sleep(1000);
- }
-
- if (got < totalGet)
- {
- _waveOutStream.Position = 0; // loop if the file ends
- }
-
- pos += got;
- }
- }
- else
- {
- for (var i = 0; i < buffer.Length; i++)
- {
- buffer[i] = 0;
- }
- }
-
- Marshal.Copy(buffer, 0, data, size);
- }
-
- private void Dispose()
- {
- if (_wavPlayer == null) return;
- try
- {
- _wavPlayer.Dispose();
- }
- finally
- {
- _wavPlayer = null;
- }
- }
-
- ~PlayWav()
- {
- Dispose();
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOut.cs b/Correlator/Util/WaveOut.cs
deleted file mode 100644
index df51931..0000000
--- a/Correlator/Util/WaveOut.cs
+++ /dev/null
@@ -1,288 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Correlator.Util
-{
- internal static class WaveOutHelper
- {
- public static void Try(int err)
- {
- if (err != WaveOutBase.MmsyserrNoerror)
- throw new Exception(err.ToString());
- }
- }
-
- public delegate void BufferFillEventHandler(IntPtr data, int size);
-
- internal class WaveOutBuffer : IDisposable
- {
- public WaveOutBuffer NextBuffer;
-
- private readonly AutoResetEvent _mPlayEvent = new AutoResetEvent(false);
- private readonly IntPtr _mWaveOut;
-
- private WaveOutBase.WaveHdr _mHeader;
- private GCHandle _mHeaderHandle;
- private GCHandle _mHeaderDataHandle;
-
- private int _mark;
-
- private bool _mPlaying;
-
- internal static void WaveOutProc(IntPtr hdrvr, int uMsg, int dwUser, ref WaveOutBase.WaveHdr wavhdr,
- int dwParam2)
- {
- if (uMsg != WaveOutBase.MmWomDone) return;
- try
- {
- var h = (GCHandle)wavhdr.dwUser;
- var buf = (WaveOutBuffer)h.Target;
- buf.OnCompleted();
- }
- catch (Exception e)
- {
- "WaveOut".WriteLog(e.Message);
- }
- }
-
- public WaveOutBuffer(IntPtr waveOutHandle, int size)
- {
- _mWaveOut = waveOutHandle;
-
- _mHeaderHandle = GCHandle.Alloc(_mHeader, GCHandleType.Pinned);
- _mHeader.dwUser = (IntPtr)GCHandle.Alloc(this);
- var mHeaderData = new byte[size];
- _mHeaderDataHandle = GCHandle.Alloc(mHeaderData, GCHandleType.Pinned);
- _mHeader.lpData = _mHeaderDataHandle.AddrOfPinnedObject();
- _mHeader.dwBufferLength = size;
- WaveOutHelper.Try(WaveOutBase.waveOutPrepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)));
- }
-
- public void Set(int mark)
- {
- _mark = mark;
- }
-
- ~WaveOutBuffer()
- {
- Dispose();
- }
-
- public void Dispose()
- {
- if (_mHeader.lpData != IntPtr.Zero)
- {
- WaveOutBase.waveOutUnprepareHeader(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader));
- _mHeaderHandle.Free();
- _mHeader.lpData = IntPtr.Zero;
- }
-
- _mPlayEvent.Close();
- if (_mHeaderDataHandle.IsAllocated)
- _mHeaderDataHandle.Free();
- GC.SuppressFinalize(this);
- }
-
- public int Size => _mHeader.dwBufferLength;
-
- public IntPtr Data => _mHeader.lpData;
-
- private void GetMemory(string title)
- {
- "WaveOut".WriteLog($"{title}: {_mPlaying}, {_mark}");
- }
-
- public bool Play()
- {
- lock (this)
- {
- GetMemory("Play");
- _mPlayEvent.Reset();
- _mPlaying = WaveOutBase.waveOutWrite(_mWaveOut, ref _mHeader, Marshal.SizeOf(_mHeader)) ==
- WaveOutBase.MmsyserrNoerror;
- return _mPlaying;
- }
- }
-
- public void WaitFor()
- {
- GetMemory("WaitFor");
- if (_mPlaying)
- {
- _mPlaying = _mPlayEvent.WaitOne();
- }
- }
-
- private void OnCompleted()
- {
- GetMemory("OnCompleted");
- _mPlayEvent.Set();
- _mPlaying = false;
- }
- }
-
- public class WaveOut : IDisposable
- {
- private IntPtr _mWaveOut;
- private WaveOutBuffer _mBuffers; // linked list
- private WaveOutBuffer _mCurrentBuffer;
- private Task _mThread;
- private BufferFillEventHandler _mFillProc;
- private bool _mFinished;
-
- private bool _mPause;
-
- //public bool bPause
- //{
- // get { return m_Pause; }
- // set { m_Pause = value; }
- //}
- private readonly byte _mZero;
-
- private readonly WaveOutBase.WaveDelegate _mBufferProc = WaveOutBuffer.WaveOutProc;
-
- public static int DeviceCount => WaveOutBase.waveOutGetNumDevs();
-
- public WaveOut(int device, WaveFormat format, int bufferSize, int bufferCount, BufferFillEventHandler fillProc)
- {
- _mZero = format.wBitsPerSample == 8 ? (byte)128 : (byte)0;
- _mFillProc = fillProc;
- WaveOutHelper.Try(WaveOutBase.waveOutOpen(out _mWaveOut, device, format, _mBufferProc, 0,
- WaveOutBase.CallbackFunction));
- AllocateBuffers(bufferSize, bufferCount);
-
- _mThread = new Task(ThreadProc);
- _mThread.Start();
- }
-
- ~WaveOut()
- {
- Dispose();
- }
-
- public void Pause()
- {
- _mPause = true;
- WaveOutBase.waveOutPause(_mWaveOut);
- //WaveOutBase.waveOutReset(m_WaveOut);
- }
-
- public void Resume()
- {
- _mPause = false;
- WaveOutBase.waveOutRestart(_mWaveOut);
- }
-
- public void Dispose()
- {
- if (_mThread != null)
- try
- {
- _mPause = false;
- _mFinished = true;
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutReset(_mWaveOut);
-
- _mFillProc = null;
- FreeBuffers();
- if (_mWaveOut != IntPtr.Zero)
- WaveOutBase.waveOutClose(_mWaveOut);
- }
- finally
- {
- _mThread = null;
- _mWaveOut = IntPtr.Zero;
- }
-
- GC.SuppressFinalize(this);
- }
-
- private void ThreadProc()
- {
- _mPause = false;
- while (!_mFinished)
- {
- // pause
- while (_mPause)
- {
- Thread.Sleep(10);
- }
-
- Advance();
- if (_mFillProc != null && !_mFinished)
- {
- _mFillProc(_mCurrentBuffer.Data, _mCurrentBuffer.Size);
- }
- else if (_mCurrentBuffer != null)
- {
- // zero out buffer
- var b = new byte[_mCurrentBuffer.Size];
- for (var i = 0; i < b.Length; i++)
- b[i] = _mZero;
- Marshal.Copy(b, 0, _mCurrentBuffer.Data, b.Length);
- }
-
- _mCurrentBuffer?.Play();
- }
-
- WaitForAllBuffers();
- }
-
- private void AllocateBuffers(int bufferSize, int bufferCount)
- {
- FreeBuffers();
- if (bufferCount <= 0) return;
- _mBuffers = new WaveOutBuffer(_mWaveOut, bufferSize);
- _mBuffers.Set(0);
- var prev = _mBuffers;
- try
- {
- for (var i = 1; i < bufferCount; i++)
- {
- var buf = new WaveOutBuffer(_mWaveOut, bufferSize);
- buf.Set(i);
- prev.NextBuffer = buf;
- prev = buf;
- }
- }
- finally
- {
- prev.NextBuffer = _mBuffers;
- }
- }
-
- private void FreeBuffers()
- {
- _mCurrentBuffer = null;
- if (_mBuffers == null) return;
- var first = _mBuffers;
- _mBuffers = null;
-
- var current = first;
- do
- {
- var next = current.NextBuffer;
- current.Dispose();
- current = next;
- } while (current != first);
- }
-
- private void Advance()
- {
- _mCurrentBuffer = _mCurrentBuffer == null ? _mBuffers : _mCurrentBuffer.NextBuffer;
- _mCurrentBuffer?.WaitFor();
- }
-
- private void WaitForAllBuffers()
- {
- var buf = _mBuffers;
- while (_mBuffers != null && buf.NextBuffer != _mBuffers)
- {
- buf.WaitFor();
- buf = buf.NextBuffer;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutBase.cs b/Correlator/Util/WaveOutBase.cs
deleted file mode 100644
index 4ce1442..0000000
--- a/Correlator/Util/WaveOutBase.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-
-namespace Correlator.Util
-{
- public enum WaveFormats
- {
- Pcm = 1,
- Float = 3
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class WaveFormat
- {
- public readonly short wFormatTag;
- public readonly short nChannels;
- public readonly int nSamplesPerSec;
- public readonly int nAvgBytesPerSec;
- public readonly short nBlockAlign;
- public readonly short wBitsPerSample;
- public readonly short cbSize;
-
- public WaveFormat(int rate, int bits, int channels)
- {
- wFormatTag = (short)WaveFormats.Pcm;
- nChannels = (short)channels;
- nSamplesPerSec = rate;
- wBitsPerSample = (short)bits;
- cbSize = 0;
-
- nBlockAlign = (short)(channels * (bits / 8));
- nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;
- }
- }
-
- internal static class WaveOutBase
- {
- public const int MmsyserrNoerror = 0; // no error
-
- public const int MmWomOpen = 0x3BB;
- public const int MmWomClose = 0x3BC;
- public const int MmWomDone = 0x3BD;
-
- public const int CallbackFunction = 0x00030000; // dwCallback is a FARPROC
-
- public const int TimeMs = 0x0001; // time in milliseconds
- public const int TimeSamples = 0x0002; // number of wave samples
- public const int TimeBytes = 0x0004; // current byte offset
-
- // callbacks
- public delegate void WaveDelegate(IntPtr hdrvr, int uMsg, int dwUser, ref WaveHdr wavhdr, int dwParam2);
-
- // structs
-
- [StructLayout(LayoutKind.Sequential)]
- public struct WaveHdr
- {
- public IntPtr lpData; // pointer to locked data buffer
- public int dwBufferLength; // length of data buffer
- public readonly int dwBytesRecorded; // used for input only
- public IntPtr dwUser; // for client's use+
- public readonly int dwFlags; // assorted flags (see defines)
- public readonly int dwLoops; // loop control counter
- public readonly IntPtr lpNext; // PWaveHdr, reserved for driver
- public readonly int reserved; // reserved for driver
- }
-
- private const string Mmdll = "winmm.dll";
-
- // native calls
- [DllImport(Mmdll)]
- public static extern int waveOutGetNumDevs();
-
- [DllImport(Mmdll)]
- public static extern int waveOutPrepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutUnprepareHeader(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutWrite(IntPtr hWaveOut, ref WaveHdr lpWaveOutHdr, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutOpen(out IntPtr hWaveOut, int uDeviceID, WaveFormat lpFormat,
- WaveDelegate dwCallback, int dwInstance, int dwFlags);
-
- [DllImport(Mmdll)]
- public static extern int waveOutReset(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutClose(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutPause(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutRestart(IntPtr hWaveOut);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetPosition(IntPtr hWaveOut, out int lpInfo, int uSize);
-
- [DllImport(Mmdll)]
- public static extern int waveOutSetVolume(IntPtr hWaveOut, int dwVolume);
-
- [DllImport(Mmdll)]
- public static extern int waveOutGetVolume(IntPtr hWaveOut, out int dwVolume);
- }
-}
\ No newline at end of file
diff --git a/Correlator/Util/WaveOutStream.cs b/Correlator/Util/WaveOutStream.cs
deleted file mode 100644
index 497f779..0000000
--- a/Correlator/Util/WaveOutStream.cs
+++ /dev/null
@@ -1,159 +0,0 @@
-using System;
-using System.IO;
-using System.Text;
-
-namespace Correlator.Util
-{
- public class WaveOutStream : Stream, IDisposable
- {
- private readonly Stream _mStream;
- private const int BufferSize = 7500 * 3 * 3600; //10 * 1024 *1024;
- private readonly byte[] _streamBuffer = new byte[BufferSize];
- private int _head;
- private int _tail;
-
- public WaveFormat Format { get; set; }
-
- private string ReadChunk(BinaryReader reader)
- {
- var ch = new byte[4];
- reader.Read(ch, 0, ch.Length);
- return Encoding.ASCII.GetString(ch);
- }
-
- public WaveOutStream(string fileName) : this(new FileStream(fileName, FileMode.OpenOrCreate))
- {
- }
-
- private WaveOutStream(Stream s)
- {
- _mStream = s;
- Format = new WaveFormat(7500, 24, 1); // initialize to any format
- }
-
- ~WaveOutStream()
- {
- Dispose();
- }
-
- public new void Dispose()
- {
- _mStream?.Close();
- GC.SuppressFinalize(this);
- }
-
- public override bool CanRead => true;
-
- public override bool CanSeek => true;
-
- public override bool CanWrite => false;
-
- public override long Length => 0;
-
- public override long Position
- {
- get => _mStream.Position;
- set => Seek(value, SeekOrigin.Begin);
- }
-
- public override void Close()
- {
- Dispose();
- }
-
- public override void Flush()
- {
- }
-
- public override void SetLength(long len)
- {
- throw new InvalidOperationException();
- }
-
- public override long Seek(long pos, SeekOrigin o)
- {
- switch (o)
- {
- case SeekOrigin.Begin:
- _mStream.Position = pos;
- break;
- case SeekOrigin.Current:
- _mStream.Seek(pos, SeekOrigin.Current);
- break;
- case SeekOrigin.End:
- _mStream.Position = pos;
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(o), o, null);
- }
-
- return Position;
- }
- //public override int Read(byte[] buf, int ofs, int count)
- //{
- // int toread = (int)Math.Min(count, m_Length - Position);
- // return m_Stream.Read(buf, ofs, toread);
- //}
- //public override void Write(byte[] buf, int ofs, int count)
- //{
- // throw new InvalidOperationException();
- //}
-
- // add for socket
- public override int Read(byte[] buf, int ofs, int count)
- {
- lock (this)
- {
- var leftSize = (BufferSize + _tail - _head) % BufferSize;
- if (leftSize < count)
- {
- // Console.WriteLine("left_size: {0}", left_size);
- return 0;
- }
-
- var tailSize = BufferSize - _head;
- var headSize = count - tailSize;
- if (tailSize < count)
- {
- Array.Copy(_streamBuffer, _head, buf, ofs, tailSize);
- Array.Copy(_streamBuffer, 0, buf, ofs + tailSize - 1, headSize);
- }
- else
- {
- Array.Copy(_streamBuffer, _head, buf, ofs, count);
- }
-
- _head = (_head + count) % BufferSize;
- }
-
- return count;
- }
-
-
- public override void Write(byte[] buf, int ofs, int count)
- {
- lock (this)
- {
- var emptySize = BufferSize - 1 - (BufferSize + _tail - _head) % BufferSize;
- if (emptySize < count)
- {
- return;
- }
-
- var tailSize = BufferSize - _tail - 1;
- var headSize = count - tailSize;
- if (tailSize < count)
- {
- Array.Copy(buf, ofs, _streamBuffer, _tail, tailSize);
- Array.Copy(buf, ofs + tailSize - 1, _streamBuffer, 0, headSize);
- }
- else
- {
- Array.Copy(buf, ofs, _streamBuffer, _tail, count);
- }
-
- _tail = (_tail + count) % BufferSize;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Correlator/ViewModels/AuditionViewModel.cs b/Correlator/ViewModels/AuditionViewModel.cs
index 19c2ae8..74376fa 100644
--- a/Correlator/ViewModels/AuditionViewModel.cs
+++ b/Correlator/ViewModels/AuditionViewModel.cs
@@ -1,6 +1,7 @@
using System;
using System.Runtime.InteropServices;
using Correlator.DataService;
+using Correlator.Events;
using Correlator.SensorHubTag;
using Correlator.Util;
using NAudio.CoreAudioApi;
@@ -81,30 +82,30 @@
BlueSensorMuteCommand = new DelegateCommand(SetCurrentMicVolume);
//音频监听
- // LazyWaveIn.Value.DataAvailable += delegate(object sender, WaveInEventArgs args)
- // {
- // _isStartRecording = true;
- //
- // var buffer = args.Buffer;
- //
- // var sts = new float[buffer.Length / 2];
- // var outIndex = 0;
- // for (var i = 0; i < buffer.Length; i += 2)
- // {
- // sts[outIndex++] = BitConverter.ToInt16(buffer, i) / 32768f;
- // }
- //
- // if (FlowStatus.CurrentListenSoundDevCode == DevCode.Dev1)
- // {
- // eventAggregator.GetEvent().Publish(sts);
- // }
- // else
- // {
- // eventAggregator.GetEvent().Publish(sts);
- // }
- // };
- //
- // LazyWaveIn.Value.RecordingStopped += delegate { _isStartRecording = false; };
+ LazyWaveIn.Value.DataAvailable += delegate(object sender, WaveInEventArgs args)
+ {
+ _isStartRecording = true;
+
+ var buffer = args.Buffer;
+
+ var sts = new float[buffer.Length / 2];
+ var outIndex = 0;
+ for (var i = 0; i < buffer.Length; i += 2)
+ {
+ sts[outIndex++] = BitConverter.ToInt16(buffer, i) / 32768f;
+ }
+
+ if (FlowStatus.CurrentListenSoundDevCode == DevCode.Dev1)
+ {
+ eventAggregator.GetEvent().Publish(sts);
+ }
+ else
+ {
+ eventAggregator.GetEvent().Publish(sts);
+ }
+ };
+
+ LazyWaveIn.Value.RecordingStopped += delegate { _isStartRecording = false; };
}
///
diff --git a/Correlator/Views/AuditionView.xaml.cs b/Correlator/Views/AuditionView.xaml.cs
index 27cf9c2..9fca3f0 100644
--- a/Correlator/Views/AuditionView.xaml.cs
+++ b/Correlator/Views/AuditionView.xaml.cs
@@ -15,17 +15,16 @@
InitializeComponent();
var redSensorPlot = RedSensorScottPlotChart.Plot;
+ //去掉网格线
+ redSensorPlot.Grid(false);
//去掉四周坐标轴
- redSensorPlot.XAxis.IsVisible = false;
- redSensorPlot.XAxis2.IsVisible = false;
- redSensorPlot.YAxis.IsVisible = false;
- redSensorPlot.YAxis2.IsVisible = false;
+ redSensorPlot.Frameless();
var blueSensorPlot = BlueSensorScottPlotChart.Plot;
- blueSensorPlot.XAxis.IsVisible = false;
- blueSensorPlot.XAxis2.IsVisible = false;
- blueSensorPlot.YAxis.IsVisible = false;
- blueSensorPlot.YAxis2.IsVisible = false;
+ //去掉网格线
+ blueSensorPlot.Grid(false);
+ //去掉四周坐标轴
+ blueSensorPlot.Frameless();
eventAggregator.GetEvent().Subscribe(delegate(float[] floats)
{
@@ -34,16 +33,16 @@
{
RedSensorScottPlotChart.Plot.Clear();
RedSensorScottPlotChart.Refresh();
-
+
var xDoubles = new List();
var yDoubles = new List();
-
+
for (var i = 0; i < floats.Length; i++)
{
xDoubles.Add(i);
yDoubles.Add(floats[i]);
}
-
+
RedSensorScottPlotChart.Plot.AddSignalXY(xDoubles.ToArray(), yDoubles.ToArray(), Color.LimeGreen);
RedSensorScottPlotChart.Refresh();
}
@@ -51,16 +50,16 @@
{
BlueSensorScottPlotChart.Plot.Clear();
BlueSensorScottPlotChart.Refresh();
-
+
var xDoubles = new List();
var yDoubles = new List();
-
+
for (var i = 0; i < floats.Length; i++)
{
xDoubles.Add(i);
yDoubles.Add(floats[i]);
}
-
+
BlueSensorScottPlotChart.Plot.AddSignalXY(xDoubles.ToArray(), yDoubles.ToArray(), Color.LimeGreen);
BlueSensorScottPlotChart.Refresh();
}
diff --git a/Correlator/Views/MainWindow.xaml.cs b/Correlator/Views/MainWindow.xaml.cs
index 7386767..4b8584b 100644
--- a/Correlator/Views/MainWindow.xaml.cs
+++ b/Correlator/Views/MainWindow.xaml.cs
@@ -8,7 +8,6 @@
using Prism.Events;
using ScottPlot;
using ScottPlot.Plottable;
-using MessageBox = HandyControl.Controls.MessageBox;
namespace Correlator.Views
{