当前位置:编程学习 > C#/ASP.NET >>

帮我读读代码?

我是个新手,从网上下了一段录音的程序,里面有API函数还有线程的东西,请哪位高手帮我读一下,最好注明每一句代码的意思和程序的流程。运行了一下程序,实在搞不懂程序按什么顺序执行?
代码如下:
Form1代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace MaxCo
{
    public partial class Form1 : Form
    {
        IWaveControl wave;

        public Form1()
        {
            InitializeComponent();
            wave = new Wave();
        }

        private void btnRecord_Click(object sender, EventArgs e)
        {
            wave.SavedFile = "e:/Test1.wav";
            wave.Start();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            wave.Stop();
        }
    }
} --------------------编程问答-------------------- WaveNative类:

using System;
using System.Runtime.InteropServices;

namespace MaxCo
{
    internal class WaveNative
    {
        // consts
        public const int MMSYSERR_NOERROR = 0; // no error

        public const int MM_WOM_OPEN = 0x3BB;
        public const int MM_WOM_CLOSE = 0x3BC;
        public const int MM_WOM_DONE = 0x3BD;

        public const int MM_WIM_OPEN = 0x3BE;
        public const int MM_WIM_CLOSE = 0x3BF;
        public const int MM_WIM_DATA = 0x3C0;

        public const int CALLBACK_FUNCTION = 0x00030000;    // dwCallback is a FARPROC 

        public const int TIME_MS = 0x0001;  // time in milliseconds 
        public const int TIME_SAMPLES = 0x0002;  // number of wave samples 
        public const int TIME_BYTES = 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 int dwBytesRecorded; // used for input only
            public IntPtr dwUser; // for client's use
            public int dwFlags; // assorted flags (see defines)
            public int dwLoops; // loop control counter
            public IntPtr lpNext; // PWaveHdr, reserved for driver
            public int reserved; // reserved for driver
        }

        private const string mmdll = "winmm.dll";

        // WaveOut 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);

        // WaveIn calls
        [DllImport(mmdll)]
        public static extern int waveInGetNumDevs();
        [DllImport(mmdll)]
        public static extern int waveInAddBuffer(IntPtr hwi, ref WaveHdr pwh, int cbwh);
        [DllImport(mmdll)]
        public static extern int waveInClose(IntPtr hwi);
        [DllImport(mmdll)]
        public static extern int waveInOpen(out IntPtr phwi, int uDeviceID, WaveFormat lpFormat, WaveDelegate dwCallback, int dwInstance, int dwFlags);
        [DllImport(mmdll)]
        public static extern int waveInPrepareHeader(IntPtr hWaveIn, ref WaveHdr lpWaveInHdr, int uSize);
        [DllImport(mmdll)]
        public static extern int waveInUnprepareHeader(IntPtr hWaveIn, ref WaveHdr lpWaveInHdr, int uSize);
        [DllImport(mmdll)]
        public static extern int waveInReset(IntPtr hwi);
        [DllImport(mmdll)]
        public static extern int waveInStart(IntPtr hwi);
        [DllImport(mmdll)]
        public static extern int waveInStop(IntPtr hwi);
    }
}
--------------------编程问答-------------------- WaveIn类:

using System;
using System.Threading;
using System.Runtime.InteropServices;

namespace MaxCo
{
    internal class WaveInHelper
    {
        public static void Try(int err)
        {
            if (err != WaveNative.MMSYSERR_NOERROR)
                throw new Exception(err.ToString());
        }
    }

    public delegate void BufferDoneEventHandler(IntPtr data, int size);

    internal class WaveInBuffer : IDisposable
    {
        public WaveInBuffer NextBuffer;

        private AutoResetEvent m_RecordEvent = new AutoResetEvent(false);
        private IntPtr m_WaveIn;

        private WaveNative.WaveHdr m_Header;
        private byte[] m_HeaderData;
        private GCHandle m_HeaderHandle;
        private GCHandle m_HeaderDataHandle;

        private bool m_Recording;

        internal static void WaveInProc(IntPtr hdrvr, int uMsg, int dwUser, ref WaveNative.WaveHdr wavhdr, int dwParam2)
        {
            if (uMsg == WaveNative.MM_WIM_DATA)
            {
                try
                {
                    GCHandle h = (GCHandle)wavhdr.dwUser;
                    WaveInBuffer buf = (WaveInBuffer)h.Target;
                    buf.OnCompleted();
                }
                catch
                {
                }
            }
        }

        public WaveInBuffer(IntPtr waveInHandle, int size)
        {
            m_WaveIn = waveInHandle;

            m_HeaderHandle = GCHandle.Alloc(m_Header, GCHandleType.Pinned);
            m_Header.dwUser = (IntPtr)GCHandle.Alloc(this);
            m_HeaderData = new byte[size];
            m_HeaderDataHandle = GCHandle.Alloc(m_HeaderData, GCHandleType.Pinned);
            m_Header.lpData = m_HeaderDataHandle.AddrOfPinnedObject();
            m_Header.dwBufferLength = size;
            WaveInHelper.Try(WaveNative.waveInPrepareHeader(m_WaveIn, ref m_Header, Marshal.SizeOf(m_Header)));
        }

        ~WaveInBuffer()
        {
            Dispose();
        }

        public void Dispose()
        {
            if (m_Header.lpData != IntPtr.Zero)
            {
                WaveNative.waveInUnprepareHeader(m_WaveIn, ref m_Header, Marshal.SizeOf(m_Header));
                m_HeaderHandle.Free();
                m_Header.lpData = IntPtr.Zero;
            }
            m_RecordEvent.Close();
            if (m_HeaderDataHandle.IsAllocated)
                m_HeaderDataHandle.Free();
            GC.SuppressFinalize(this);
        }

        public int Size
        {
            get { return m_Header.dwBufferLength; }
        }

        public IntPtr Data
        {
            get { return m_Header.lpData; }
        }

        public bool Record()
        {
            lock (this)
            {
                m_RecordEvent.Reset();
                m_Recording = WaveNative.waveInAddBuffer(m_WaveIn, ref m_Header, Marshal.SizeOf(m_Header)) == WaveNative.MMSYSERR_NOERROR;
                return m_Recording;
            }
        }

        public void WaitFor()
        {
            if (m_Recording)
                m_Recording = m_RecordEvent.WaitOne();
            else
                Thread.Sleep(0);
        }

        private void OnCompleted()
        {
            m_RecordEvent.Set();
            m_Recording = false;
        }
    }

    public class WaveInRecorder : IDisposable
    {
        private IntPtr m_WaveIn;
        private WaveInBuffer m_Buffers; // linked list
        private WaveInBuffer m_CurrentBuffer;
        private Thread m_Thread;
        private BufferDoneEventHandler m_DoneProc;
        private bool m_Finished;
        private bool m_IsSupend;

        private WaveNative.WaveDelegate m_BufferProc = new WaveNative.WaveDelegate(WaveInBuffer.WaveInProc);

        public static int DeviceCount
        {
            get { return WaveNative.waveInGetNumDevs(); }
        }

        public WaveInRecorder(int device, WaveFormat format, int bufferSize, int bufferCount, BufferDoneEventHandler doneProc)
        {
            m_DoneProc = doneProc;
            WaveInHelper.Try(WaveNative.waveInOpen(out m_WaveIn, device, format, m_BufferProc, 0, WaveNative.CALLBACK_FUNCTION));
            AllocateBuffers(bufferSize, bufferCount);
            for (int i = 0; i < bufferCount; i++)
            {
                SelectNextBuffer();
                m_CurrentBuffer.Record();
            }
            WaveInHelper.Try(WaveNative.waveInStart(m_WaveIn));
            m_Thread = new Thread(new ThreadStart(ThreadProc));
            m_Thread.Start();
        }

        ~WaveInRecorder()
        {
            Dispose();
        }

        public void Dispose()
        {
            if (m_Thread != null)
                try
                {
                    m_Finished = true;
                    if (m_WaveIn != IntPtr.Zero)
                        WaveNative.waveInReset(m_WaveIn);
                    WaitForAllBuffers();
                    m_Thread.Join();
                    m_DoneProc = null;
                    FreeBuffers();
                    if (m_WaveIn != IntPtr.Zero)
                        WaveNative.waveInClose(m_WaveIn);
                }
                finally
                {
                    m_Thread = null;
                    m_WaveIn = IntPtr.Zero;
                }
            GC.SuppressFinalize(this);
        }

        private void ThreadProc()
        {
            while (!m_Finished)
            {
                Advance();
                if (m_DoneProc != null && !m_Finished)
                    m_DoneProc(m_CurrentBuffer.Data, m_CurrentBuffer.Size);
                m_CurrentBuffer.Record();
            }
        }

        private void AllocateBuffers(int bufferSize, int bufferCount)
        {
            FreeBuffers();
            if (bufferCount > 0)
            {
                m_Buffers = new WaveInBuffer(m_WaveIn, bufferSize);
                WaveInBuffer Prev = m_Buffers;
                try
                {
                    for (int i = 1; i < bufferCount; i++)
                    {
                        WaveInBuffer Buf = new WaveInBuffer(m_WaveIn, bufferSize);
                        Prev.NextBuffer = Buf;
                        Prev = Buf;
                    }
                }
                finally
                {
                    Prev.NextBuffer = m_Buffers;
                }
            }
        }

        private void FreeBuffers()
        {
            m_CurrentBuffer = null;
            if (m_Buffers != null)
            {
                WaveInBuffer First = m_Buffers;
                m_Buffers = null;

                WaveInBuffer Current = First;
                do
                {
                    WaveInBuffer Next = Current.NextBuffer;
                    Current.Dispose();
                    Current = Next;
                } while (Current != First);
            }
        }

        private void Advance()
        {
            SelectNextBuffer();
            m_CurrentBuffer.WaitFor();
        }

        private void SelectNextBuffer()
        {
            m_CurrentBuffer = m_CurrentBuffer == null ? m_Buffers : m_CurrentBuffer.NextBuffer;
        }

        private void WaitForAllBuffers()
        {
            WaveInBuffer Buf = m_Buffers;
            while (Buf.NextBuffer != m_Buffers)
            {
                Buf.WaitFor();
                Buf = Buf.NextBuffer;
            }
        }
    }
}
--------------------编程问答-------------------- Wave类:
using System;
using System.Collections;
using System.ComponentModel;
using System.IO;

namespace MaxCo
{
    /// <summary>
    /// Wave 概要説明
    /// </summary>
    public class Wave : IWaveControl
    {
        private WaveInRecorder m_Recorder;
        private WaveFormat m_Format;

        System.IO.BinaryWriter bw_tmp;
        private string tmpName = "tmp.wav";
        private FileStream fs_tmp;
        private byte[] m_RecBuffer;

        public Wave()
        {

        }

        private void DataArrived(IntPtr data, int size)
        {
            try
            {
                if (m_RecBuffer == null || m_RecBuffer.Length < size)
                {
                    m_RecBuffer = new byte[size];
                }
                System.Runtime.InteropServices.Marshal.Copy(data, m_RecBuffer, 0, size);

                bw_tmp.Write(m_RecBuffer);
                _recordSize += m_RecBuffer.Length;
            }
            catch (Exception e)
            {
                return;
            }
        }

        private void WriteToFile()
        {
            FileStream fs = null;
            BinaryReader br = null;
            FileStream fs_2 = null;
            BinaryWriter bw = null;
            bool _isFinish = false;

            try
            {
                fs = new FileStream(tmpName, FileMode.Open);
                br = new BinaryReader(fs);

                fs_2 = new FileStream(SavedFile, FileMode.Create);
                bw = new BinaryWriter(fs_2);

                long chunksize = fs.Length + 36;
                WriteChars(bw, "RIFF");
                bw.Write((int)chunksize);
                WriteChars(bw, "WAVE");
                WriteChars(bw, "fmt ");
                bw.Write((int)16);
                bw.Write(m_Format.wFormatTag);
                bw.Write(m_Format.nChannels);
                bw.Write(m_Format.nSamplesPerSec);
                bw.Write(m_Format.nAvgBytesPerSec);
                bw.Write(m_Format.nBlockAlign);
                bw.Write(m_Format.wBitsPerSample);
                WriteChars(bw, "data");
                bw.Write(fs.Length);
                bw.Flush();

                byte[] bytes = new byte[512];
                while (true)
                {
                    if (br.Read(bytes, 0, bytes.Length) > 0)
                    {
                        bw.Write(bytes);
                    }
                    else
                    {
                        break;
                    }
                }

                _isFinish = true;

            }
            catch (Exception e)
            {
                OnError(e, "ファイル入力異常!");
            }
            finally
            {
                if (br != null) br.Close();
                if (bw != null) bw.Close();

                System.Threading.Thread.Sleep(500);

                if (_isFinish)
                {
                    FileInfo fi = new FileInfo(tmpName);
                    fi.Delete();
                }
            }

        }

        private void WriteChars(BinaryWriter wrtr, string text)
        {
            for (int i = 0; i < text.Length; i++)
            {
                char c = (char)text[i];
                wrtr.Write(c);
            }
        }

        /// <summary>
        /// 録音停止
        /// </summary>
        public void Stop()
        {
            if (m_Recorder != null)
            {
                try
                {
                    bw_tmp.Close();
                    m_Recorder.Dispose();


                    WriteToFile();

                    _recordSize = 0;
                    _isRecord = false;
                }
                finally
                {
                    m_Recorder = null;
                }
            }
        }

        /// <summary>
        /// 録音開始
        /// </summary>
        public void Start()
        {
            if (_isRecord) return;
            Stop();
            try
            {
                FileInfo file = new FileInfo(tmpName);
                if (file.Exists)
                {
                    file.Delete();
                }
                fs_tmp = new FileStream(tmpName, System.IO.FileMode.Create);
                bw_tmp = new BinaryWriter(fs_tmp);

                _isRecord = true;

                m_Format = new WaveFormat(11025, 8, 1);

                m_Recorder = new WaveInRecorder(-1, m_Format, 16384, 3, new BufferDoneEventHandler(DataArrived));

            }
            catch (Exception e)
            {
                OnError(e, "録音起動失敗!");
                Stop();
            }
        }


        #region IWaveRecordInfo 

        private string _saveFile = null;
        public string SavedFile
        {
            get
            {
                return _saveFile;
            }
            set
            {
                _saveFile = value;
            }
        }

        public string RecordTmpFile
        {
            get
            {
                return tmpName;
            }
        }

        private long _recordSize = 36;
        public long RecordSize
        {
            get
            {
                return _recordSize;
            }
        }

        private bool _isRecord = false;
        public bool IsRecord
        {
            get
            {
                return _isRecord;
            }
        }

        #endregion

        #region IWaveControl 

        public event ErrorEventHandle ErrorEvent;

        private void OnError(Exception e, string error)
        {
            if (ErrorEvent != null)
                ErrorEvent(e, error);
        }
        #endregion
    }
}
--------------------编程问答-------------------- 一分都不给
给你个地址,这里的这份代码和你的一样的,这里有注释,自己去看
http://read.pudn.com/downloads90/sourcecode/speech/344871/SoundDone/WaveOut.cs__.htm --------------------编程问答-------------------- 等牛人帮你看吧
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,