Managed DirectSoundを使ってマイクから音声を録音してみる2

chakemiです。予想通り風邪を引いてしまいました。。。喉が痛い。。。 そんな中、本日は、前回未完成に終わったManaged DirectSoundを使ってマイクから音声のキャプチャですが、とりあえず、どうにか動くとこまで出来ました。

開発環境

  • WindowsXP SP3
  • VisualC#2010Express

前回、大まかにWaveFormatの生成、Device情報から、Captureオブジェクトの作成、captureBufferDescriptionインスタンスの生成まで書きました。 今回はこれらをもとに、CaptureBufferインスタンスを生成し

1
captureBuffer = new CaptureBuffer(captureBufferDescription, capture);

バッファの更新の通知を登録します。

1
2
3
4
5
6
7
8
9
autoResetEvent = new AutoResetEvent(false);
notify = new Notify(captureBuffer);

for (int i = 0; i < NumberRecordNotifications; i++)
{
    PositionNotify[i].Offset = notifySize * (i + 1) - 1;
    PositionNotify[i].EventNotifyHandle = autoResetEvent.Handle;
}
notify.SetNotificationPositions(PositionNotify, NumberRecordNotifications);

別スレッドでイベント通知を待って、

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void CapThreadProc()
{
    while (capflag)
    {
        autoResetEvent.WaitOne(Timeout.Infinite, true);
        int offset = 0;
        int readPos, capturePos;
        captureBuffer.GetCurrentPosition(out capturePos, out readPos);
        int lockSize = notifySize - offset;
        capturePos = notifySize * notifyPos;

        if (lockSize < 0)
            lockSize += captureBufferDescription.BufferBytes;

        lockSize -= (lockSize % 2);
        if (0 == lockSize)
            return;

キャプチャされたデータを取得して、書き込みます。

1
2
3
4
5
6
7
8
byte[] captureData = (byte[])captureBuffer.Read(capturePos, typeof(byte), LockFlag.None, lockSize);

        binaryWriter.Write(captureData, 0, captureData.Length);

        notifyPos++;
        notifyPos %= NumberRecordNotifications;
    }
}

以下、ソース全体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
using System.Threading;

namespace testDirectSound2
{
    public partial class Form1 : Form
    {

        private WaveFormat waveFormat;
        private Device device;
        private CaptureDevicesCollection captureDevice;
        private Capture capture;
        private CaptureBuffer captureBuffer;
        private CaptureBufferDescription captureBufferDescription;

        private BinaryWriter binaryWriter;

        private AutoResetEvent autoResetEvent;
        private Notify notify;
        private Thread notifyThread;

        private int notifySize = 0;
        private static int notifyPos = 0;

        private const int NumberRecordNotifications = 16;

        private BufferPositionNotify[] PositionNotify = new BufferPositionNotify[NumberRecordNotifications];

        private bool capflag = false;


        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            waveFormat = new WaveFormat();
            waveFormat.Channels = 1;
            waveFormat.FormatTag = WaveFormatTag.Pcm;
            waveFormat.BitsPerSample = 16;
            waveFormat.SamplesPerSecond = 44100;
            waveFormat.BlockAlign = (short)(waveFormat.Channels * (waveFormat.BitsPerSample / (short)8));
            waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * waveFormat.SamplesPerSecond;


            device = new Device();
            device.SetCooperativeLevel(this, CooperativeLevel.Priority);
            captureDevice = new CaptureDevicesCollection();
            DeviceInformation deviceInfo = captureDevice[0];
            capture = new Capture(deviceInfo.DriverGuid);


        }


        private void button1_Click(object sender, EventArgs e)
        {
            capflag = !capflag;

            if (capflag)
            {
                RecWave();
                CreateCapBuffer();
                captureBuffer.Start(true);
            }
            else {
                captureBuffer.Stop();
                notifyThread.Abort();
            }
        }

        void CreateCapBuffer()
        {
            notifySize = waveFormat.AverageBytesPerSecond / NumberRecordNotifications;
            notifySize -= notifySize % waveFormat.BlockAlign;
            try
            {
                captureBufferDescription = new CaptureBufferDescription();
                captureBufferDescription.BufferBytes = notifySize * NumberRecordNotifications;//waveFormat.AverageBytesPerSecond;
                captureBufferDescription.WaveMapped = false;
                captureBufferDescription.ControlEffects = false;
                captureBufferDescription.Format = waveFormat;

                captureBuffer = new CaptureBuffer(captureBufferDescription, capture);


            }
            catch (Exception ex)
            {
                throw ex;
            }

            //RecWave();

            notifyThread = new Thread(new ThreadStart(CapThreadProc));
            notifyThread.Start();

            autoResetEvent = new AutoResetEvent(false);
            notify = new Notify(captureBuffer);

            for (int i = 0; i < NumberRecordNotifications; i++)
            {
                PositionNotify[i].Offset = notifySize * (i + 1) - 1;
                PositionNotify[i].EventNotifyHandle = autoResetEvent.Handle;
            }
            notify.SetNotificationPositions(PositionNotify, NumberRecordNotifications);
        }


        void RecWave()
        {

            binaryWriter = new BinaryWriter(new FileStream(@"C:\test_ds_rec.wav", FileMode.Create));

            char[] Riff = { 'R', 'I', 'F', 'F' };
            char[] Wave = { 'W', 'A', 'V', 'E' };
            char[] Fmt = { 'f', 'm', 't', ' ' };
            char[] Data = { 'd', 'a', 't', 'a' };
            short padding = 1;
            int formatLength = 0x10;
            int length = 0;
            short shBytePerSample = 2;

            binaryWriter.Write(Riff);
            binaryWriter.Write(length);
            binaryWriter.Write(Wave);
            binaryWriter.Write(Fmt);
            binaryWriter.Write(formatLength);
            binaryWriter.Write(padding);
            binaryWriter.Write(waveFormat.Channels);
            binaryWriter.Write(waveFormat.SamplesPerSecond);
            binaryWriter.Write(waveFormat.AverageBytesPerSecond);
            binaryWriter.Write(shBytePerSample);
            binaryWriter.Write(waveFormat.BitsPerSample);
            binaryWriter.Write(Data);
            binaryWriter.Write((int)0);


        }

        public void CapThreadProc()
        {
            while (capflag)
            {
                autoResetEvent.WaitOne(Timeout.Infinite, true);
                int offset = 0;
                int readPos, capturePos;
                captureBuffer.GetCurrentPosition(out capturePos, out readPos);
                int lockSize = notifySize - offset;
                capturePos = notifySize * notifyPos;

                if (lockSize < 0)
                    lockSize += captureBufferDescription.BufferBytes;

                lockSize -= (lockSize % 2);
                if (0 == lockSize)
                    return;


                byte[] captureData = (byte[])captureBuffer.Read(capturePos, typeof(byte), LockFlag.None, lockSize);

                binaryWriter.Write(captureData, 0, captureData.Length);

                notifyPos++;
                notifyPos %= NumberRecordNotifications;
            }
        }

    }
}

まだまだ、動いたというレベルで完全に理解出来ていないので、引き続き勉強しようと思います。 今回、こちらのサイトと、サンプルの「CaptureSound」を参考にさせて頂きました。

Comments