Skip to content

Instantly share code, notes, and snippets.

@SunXiaoShan
Last active July 19, 2019 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SunXiaoShan/cdc615890405a96301795f9af5b7c2d0 to your computer and use it in GitHub Desktop.
Save SunXiaoShan/cdc615890405a96301795f9af5b7c2d0 to your computer and use it in GitHub Desktop.
- (void)playBeepAudio {
// Step 1: Dispose & Stop the last queue
if (_queue) {
[self stopAudio];
[self disposeAudioQueue];
_queue = nil;
}
// Step 2: Prepare the description of audio buffer
AudioStreamBasicDescription dataformat;
dataformat.mChannelsPerFrame = ...; // mono/ stereo
dataformat.mSampleRate = ...; // sample rate
dataformat.mFormatID = kAudioFormatLinearPCM;
dataformat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
dataformat.mBytesPerPacket = 2 * dataformat.mChannelsPerFrame;
dataformat.mFramesPerPacket = 1;
dataformat.mBytesPerFrame = dataformat.mBytesPerPacket;
dataformat.mBitsPerChannel = 16;
dataformat.mReserved = 0;
OSStatus status;
uint8 *audio = ...; // audio buffer
UInt32 bufferSize = ...; // audio buffer size
// Step 3: Set up the complete callback
status = AudioQueueNewOutput(
&dataformat,
BufferCallback,
(__bridge void * _Nullable)(self),
CFRunLoopGetCurrent(),
kCFRunLoopCommonModes,
0,
&_queue
);
if (status != noErr) NSLog(@"AudioQueueNewOutput bitrate failed %d", status);
// Step 4: Allocate the buffer
AudioQueueBufferRef buffer = NULL;
status = AudioQueueAllocateBuffer(
_queue,
bufferSize,
&buffer
);
if (status != noErr) NSLog(@"AudioQueueAllocateBuffer failed %d", status);
// Step 4.1: Set up the buffer data
memset(buffer->mAudioData, 0, bufferSize);
memcpy(buffer->mAudioData, audio, bufferSize);
buffer->mAudioDataByteSize = bufferSize;
// Step 5: Fill the queue buffer
status = AudioQueueEnqueueBuffer(
_queue,
buffer,
0,
nil
);
if (status != noErr) NSLog(@"AudioQueueEnqueueBuffer failed %d", status);
// Step 6: Start to play
status = AudioQueueStart(_queue, nil);
if (status != noErr) NSLog(@"AudioQueueStart failed %d", status);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment