Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // MAAudioManager.m
- // Minimal Noise
- //
- // Created by Carlo Caione on 1/14/12.
- // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
- //
- #import "MAAudioManager.h"
- #define BUFFER_SIZE 16384
- #define BUFFER_COUNT 3
- @implementation MAAudioManager
- - (id)initWithBufferCount:(UInt32)bCount
- ofSize:(UInt32)bSize
- {
- if (self = [super init])
- {
- deviceFormat.mSampleRate = 44100;
- deviceFormat.mFormatID = kAudioFormatLinearPCM;
- deviceFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
- deviceFormat.mBytesPerPacket = 4;
- deviceFormat.mFramesPerPacket = 1;
- deviceFormat.mBytesPerFrame = 4;
- deviceFormat.mChannelsPerFrame = 2;
- deviceFormat.mBitsPerChannel = 16;
- deviceFormat.mReserved = 0;
- bufferCount = bCount;
- bufferSize = bSize;
- isPlaying = NO;
- }
- return self;
- }
- - (id)init
- {
- return [self initWithBufferCount:BUFFER_COUNT ofSize:BUFFER_SIZE];
- }
- - (void)start
- {
- OSStatus err;
- if(isPlaying == NO)
- {
- err = AudioQueueNewOutput(&deviceFormat,
- AudioQueueCallback,
- (__bridge void *) self,
- nil,
- nil,
- 0,
- &audioQueue);
- if(err != noErr)
- NSLog(@"AudioQueueNewOutput() error: %d", err);
- for (int i = 0; i < bufferCount; ++i) {
- AudioQueueBufferRef mBuffer;
- err = AudioQueueAllocateBuffer(audioQueue,
- bufferSize,
- &mBuffer);
- if (err != noErr){
- NSLog(@"AudioQueueAllocateBuffer() error: %d", err);
- break;
- }
- [noiseGenerator generateNoise:mBuffer];
- err = AudioQueueEnqueueBuffer(audioQueue, mBuffer, 0, NULL);
- if(err != noErr){
- NSLog(@"AudioQueueEnqueueBuffer() error: %d", err);
- }
- }
- err = AudioQueueStart(audioQueue, NULL);
- if (err == noErr){
- isPlaying = YES;
- } else {
- isPlaying = NO;
- NSLog(@"AudioQueueStart() error: %d", err);
- }
- } else {
- NSLog(@"Error: audio is already playing back.");
- }
- }
- - (void)stop
- {
- OSStatus err;
- err = AudioQueueStop(audioQueue, true);
- if(err != noErr) {
- NSLog(@"Error: it is not possible to stop audio.");
- } else {
- isPlaying = NO;
- }
- }
- - (void)processOutputBuffer:(AudioQueueBufferRef)buffer
- {
- OSStatus err;
- if(isPlaying == YES)
- {
- [outputLock lock];
- [noiseGenerator generateNoise:buffer];
- err = AudioQueueEnqueueBuffer(audioQueue, buffer, 0, NULL);
- if(err != noErr){
- NSLog(@"AudioQueueEnqueueBuffer() error: %d", err);
- isPlaying = NO;
- }
- [outputLock unlock];
- } else {
- [self stop];
- }
- }
- - (void)registerNoiseGenerator:(MANoise *)noiseGen
- {
- noiseGenerator = noiseGen;
- }
- @end
- void AudioQueueCallback(void* inUserData,
- AudioQueueRef inAQ,
- AudioQueueBufferRef inBuffer)
- {
- MAAudioManager *audioMngr = (__bridge MAAudioManager *) inUserData;
- [audioMngr processOutputBuffer:inBuffer];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement