Created
March 25, 2015 09:26
-
-
Save kyontan/5ac417f87a9be340c2c2 to your computer and use it in GitHub Desktop.
AudioQueueを使ってPCMを再生
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSData *recordedPcm; | |
AVAudioPlayer *player; | |
AudioQueueRef audioQueue; | |
AudioQueueBufferRef audioQueueBuffers; | |
// Queue/Buffer への追加は playPCM での1回しかしないため、コールバックでは何もしない (必要があればここで追加) | |
static void AQOutputCallback(void *userData, AudioQueueRef audioQueueRef, AudioQueueBufferRef audioQueueBufferRef) { | |
return; | |
} | |
-(void)playPCM:(NSData *)data queue:(AudioQueueRef)outQ buffer:(AudioQueueBufferRef)outQB { | |
outQB->mAudioDataByteSize = (UInt32)data.length; | |
UInt8 *audioData = (UInt8 *)outQB->mAudioData; | |
for(int i = 0; i < data.length; i++) { | |
audioData[i] = ((UInt8 *)data.bytes)[i]; | |
} | |
AudioQueueEnqueueBuffer(outQ, outQB, 0, NULL); | |
} | |
- (BOOL)startPlaying:(NSData *)data { | |
NSLog(@"%@", NSStringFromSelector(_cmd)); | |
[self stopPlaying]; | |
NSError *error = nil; | |
OSStatus status; | |
AudioStreamBasicDescription desc; // NOTE: fill this | |
status = AudioQueueNewOutput(&desc, AQOutputCallback, (__bridge void *)(self), nil, nil, 0, &audioQueue); | |
if (status != noErr) { | |
NSLog(@"AudioQueueNewOutput() ret=%ld", (long int)status); | |
} | |
status = AudioQueueAllocateBuffer(audioQueue, (UInt32)recordedPcm.length, &audioQueueBuffers); | |
if (status != noErr) { | |
NSLog(@"AudioQueueAllocateBuffer() ret=%ld", (long int)status); | |
} | |
AudioQueueStart(audioQueue, NULL); | |
[self playPCM:recordedPcm queue:audioQueue buffer:audioQueueBuffers]; | |
if(error) { | |
return FALSE; | |
} | |
self.buttonPlayingStart.enabled = NO; | |
self.buttonPlayingStop.enabled = YES; | |
return TRUE; | |
} | |
// 再生終了 | |
- (void)stopPlaying { | |
NSLog(@"%@", NSStringFromSelector(_cmd)); | |
AudioQueueStop(audioQueue, YES); | |
self.buttonPlayingStart.enabled = YES; | |
self.buttonPlayingStop.enabled = NO; | |
player = nil; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment