-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.c
116 lines (81 loc) · 3.18 KB
/
input.c
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
#include "input.h"
static void HandleInputBuffer();
static const int NUM_BUFFERS = 3; // 1
struct AQRecorderState {
AudioStreamBasicDescription mDataFormat; // 2
AudioQueueRef mQueue; // 3
AudioQueueBufferRef mBuffers[NUM_BUFFERS]; // 4
AudioFileID mAudioFile; // 5
UInt32 bufferByteSize; // 6
SInt64 mCurrentPacket; // 7
bool mIsRunning; // 8
};
static struct AQRecorderState S;
#define BUFFER_SIZE 64
bool init_input(void) {
#define PRINT_R do{\
printf("%d: r = %d\n",__LINE__, r);\
}while(0)
AudioStreamBasicDescription *fmt = &S.mDataFormat;
fmt->mFormatID = kAudioFormatLinearPCM;
fmt->mSampleRate = 44100.0;
fmt->mChannelsPerFrame = 1;
fmt->mBitsPerChannel = 32;
fmt->mBytesPerFrame = fmt->mChannelsPerFrame * sizeof (float);
fmt->mFramesPerPacket = 1;
fmt->mBytesPerPacket = fmt->mBytesPerFrame * fmt->mFramesPerPacket;
fmt->mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsNonInterleaved;
OSStatus r = 0;
r = AudioQueueNewInput(&S.mDataFormat, HandleInputBuffer, &S, NULL, kCFRunLoopCommonModes, 0, &S.mQueue);
PRINT_R;
UInt32 dataFormatSize = sizeof (S.mDataFormat);
r = AudioQueueGetProperty (
S.mQueue,
kAudioConverterCurrentInputStreamDescription,
&S.mDataFormat,
&dataFormatSize
);
S.bufferByteSize = BUFFER_SIZE;
for (int i = 0; i < NUM_BUFFERS; ++i) {
r = AudioQueueAllocateBuffer(S.mQueue, S.bufferByteSize, &S.mBuffers[i]);
PRINT_R;
r = AudioQueueEnqueueBuffer(S.mQueue, S.mBuffers[i], 0, NULL);
PRINT_R;
}
S.mCurrentPacket = 0;
return true;
}
static float in_buffer[BUFFER_SIZE];
float *get_input_data() { return in_buffer; }
static void HandleInputBuffer (
void *aqData,
AudioQueueRef inAQ,
AudioQueueBufferRef inBuffer,
const AudioTimeStamp *inStartTime,
UInt32 inNumPackets,
const AudioStreamPacketDescription *inPacketDesc
) {
struct AQRecorderState *pAqData = (struct AQRecorderState *) aqData;
if (inNumPackets == 0 && pAqData->mDataFormat.mBytesPerPacket != 0) {
inNumPackets =
inBuffer->mAudioDataByteSize / pAqData->mDataFormat.mBytesPerPacket;
}
// printf("%f\n", *(float*)inBuffer->mAudioData);
if (pAqData->mIsRunning == 0)
return;
memcpy(in_buffer, inBuffer->mAudioData, BUFFER_SIZE*sizeof(float));
AudioQueueEnqueueBuffer(pAqData->mQueue, inBuffer, 0, NULL);
}
void start_input() {
OSStatus r;
S.mIsRunning = true;
r = AudioQueueStart(S.mQueue, NULL);
PRINT_R;
}
void stop_input() {
OSStatus r;
r = AudioQueueStop(S.mQueue, true);
S.mIsRunning = false;
PRINT_R;
r = AudioQueueDispose(S.mQueue, true);
}