Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
243 changes: 243 additions & 0 deletions CocosDenshion/CDAudioManager.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
/*
Copyright (c) 2010 Steve Oldmeadow

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

$Id$
*/

#import "CocosDenshion.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000
#import <AVFoundation/AVFoundation.h>
#else
#import "CDXMacOSXSupport.h"
#endif

/** Different modes of the engine */
typedef enum {
kAMM_FxOnly, //!Other apps will be able to play audio
kAMM_FxPlusMusic, //!Only this app will play audio
kAMM_FxPlusMusicIfNoOtherAudio, //!If another app is playing audio at start up then allow it to continue and don't play music
kAMM_MediaPlayback, //!This app takes over audio e.g music player app
kAMM_PlayAndRecord //!App takes over audio and has input and output
} tAudioManagerMode;

/** Possible states of the engine */
typedef enum {
kAMStateUninitialised, //!Audio manager has not been initialised - do not use
kAMStateInitialising, //!Audio manager is in the process of initialising - do not use
kAMStateInitialised //!Audio manager is initialised - safe to use
} tAudioManagerState;

typedef enum {
kAMRBDoNothing, //Audio manager will not do anything on resign or becoming active
kAMRBStopPlay, //Background music is stopped on resign and resumed on become active
kAMRBStop //Background music is stopped on resign but not resumed - maybe because you want to do this from within your game
} tAudioManagerResignBehavior;

/** Notifications */
extern NSString * const kCDN_AudioManagerInitialised;

@interface CDAsynchInitialiser : NSOperation {}
@end

/** CDAudioManager supports two long audio source channels called left and right*/
typedef enum {
kASC_Left = 0,
kASC_Right = 1
} tAudioSourceChannel;

typedef enum {
kLAS_Init,
kLAS_Loaded,
kLAS_Playing,
kLAS_Paused,
kLAS_Stopped,
} tLongAudioSourceState;

@class CDLongAudioSource;
@protocol CDLongAudioSourceDelegate <NSObject>
@optional
/** The audio source completed playing */
- (void) cdAudioSourceDidFinishPlaying:(CDLongAudioSource *) audioSource;
/** The file used to load the audio source has changed */
- (void) cdAudioSourceFileDidChange:(CDLongAudioSource *) audioSource;
@end

/**
CDLongAudioSource represents an audio source that has a long duration which makes
it costly to load into memory for playback as an effect using CDSoundEngine. Examples
include background music and narration tracks. The audio file may or may not be compressed.
Bear in mind that current iDevices can only use hardware to decode a single compressed
audio file at a time and playing multiple compressed files will result in a performance drop
as software decompression will take place.
@since v0.99
*/
@interface CDLongAudioSource : NSObject <AVAudioPlayerDelegate, CDAudioInterruptProtocol>{
AVAudioPlayer *audioSourcePlayer;
NSString *audioSourceFilePath;
NSInteger numberOfLoops;
float volume;
id<CDLongAudioSourceDelegate> delegate;
BOOL mute;
BOOL enabled_;
BOOL backgroundMusic;
@public
BOOL systemPaused;//Used for auto resign handling
NSTimeInterval systemPauseLocation;//Used for auto resign handling
@protected
tLongAudioSourceState state;
}
@property (readonly) AVAudioPlayer *audioSourcePlayer;
@property (readonly) NSString *audioSourceFilePath;
@property (readwrite, nonatomic) NSInteger numberOfLoops;
@property (readwrite, nonatomic) float volume;
@property (assign) id<CDLongAudioSourceDelegate> delegate;
/* This long audio source functions as background music */
@property (readwrite, nonatomic) BOOL backgroundMusic;

/** Loads the file into the audio source */
-(void) load:(NSString*) filePath;
/** Plays the audio source */
-(void) play;
/** Stops playing the audio soruce */
-(void) stop;
/** Pauses the audio source */
-(void) pause;
/** Rewinds the audio source */
-(void) rewind;
/** Resumes playing the audio source if it was paused */
-(void) resume;
/** Returns whether or not the audio source is playing */
-(BOOL) isPlaying;

@end

/**
CDAudioManager manages audio requirements for a game. It provides access to a CDSoundEngine object
for playing sound effects. It provides access to two CDLongAudioSource object (left and right channel)
for playing long duration audio such as background music and narration tracks. Additionally it manages
the audio session to take care of things like audio session interruption and interacting with the audio
of other apps that are running on the device.

Requirements:
- Firmware: OS 2.2 or greater
- Files: CDAudioManager.*, CocosDenshion.*
- Frameworks: OpenAL, AudioToolbox, AVFoundation
@since v0.8
*/
@interface CDAudioManager : NSObject <CDLongAudioSourceDelegate, CDAudioInterruptProtocol, AVAudioSessionDelegate> {
CDSoundEngine *soundEngine;
CDLongAudioSource *backgroundMusic;
NSMutableArray *audioSourceChannels;
NSString* _audioSessionCategory;
BOOL _audioWasPlayingAtStartup;
tAudioManagerMode _mode;
SEL backgroundMusicCompletionSelector;
id backgroundMusicCompletionListener;
BOOL willPlayBackgroundMusic;
BOOL _mute;
BOOL _resigned;
BOOL _interrupted;
BOOL _audioSessionActive;
BOOL enabled_;

//For handling resign/become active
BOOL _isObservingAppEvents;
tAudioManagerResignBehavior _resignBehavior;
}

@property (readonly) CDSoundEngine *soundEngine;
@property (readonly) CDLongAudioSource *backgroundMusic;
@property (readonly) BOOL willPlayBackgroundMusic;

/** Returns the shared singleton */
+ (CDAudioManager *) sharedManager;
+ (tAudioManagerState) sharedManagerState;
/** Configures the shared singleton with a mode*/
+ (void) configure: (tAudioManagerMode) mode;
/** Initializes the engine asynchronously with a mode */
+ (void) initAsynchronously: (tAudioManagerMode) mode;
/** Initializes the engine synchronously with a mode, channel definition and a total number of channels */
- (id) init: (tAudioManagerMode) mode;
-(void) audioSessionInterrupted;
-(void) audioSessionResumed;
-(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle;
/** Returns true is audio is muted at a hardware level e.g user has ringer switch set to off */
-(BOOL) isDeviceMuted;
/** Returns true if another app is playing audio such as the iPod music player */
-(BOOL) isOtherAudioPlaying;
/** Sets the way the audio manager interacts with the operating system such as whether it shares output with other apps or obeys the mute switch */
-(void) setMode:(tAudioManagerMode) mode;
/** Shuts down the shared audio manager instance so that it can be reinitialised */
+(void) end;

/** Call if you want to use built in resign behavior but need to do some additional audio processing on resign active. */
- (void) applicationWillResignActive;
/** Call if you want to use built in resign behavior but need to do some additional audio processing on become active. */
- (void) applicationDidBecomeActive;

//New AVAudioPlayer API
/** Loads the data from the specified file path to the channel's audio source */
-(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel;
/** Retrieves the audio source for the specified channel */
-(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel;

//Legacy AVAudioPlayer API
/** Plays music in background. The music can be looped or not
It is recommended to use .aac files as background music since they are decoded by the device (hardware).
*/
-(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop;
/** Preloads a background music */
-(void) preloadBackgroundMusic:(NSString*) filePath;
/** Stops playing the background music */
-(void) stopBackgroundMusic;
/** Pauses the background music */
-(void) pauseBackgroundMusic;
/** Rewinds the background music */
-(void) rewindBackgroundMusic;
/** Resumes playing the background music */
-(void) resumeBackgroundMusic;
/** Returns whether or not the background music is playing */
-(BOOL) isBackgroundMusicPlaying;

-(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector;

@end

/** Fader for long audio source objects */
@interface CDLongAudioSourceFader : CDPropertyModifier{}
@end

static const int kCDNoBuffer = -1;

/** Allows buffers to be associated with file names */
@interface CDBufferManager:NSObject{
NSMutableDictionary* loadedBuffers;
NSMutableArray *freedBuffers;
CDSoundEngine *soundEngine;
int nextBufferId;
}

-(id) initWithEngine:(CDSoundEngine *) theSoundEngine;
-(int) bufferForFile:(NSString*) filePath create:(BOOL) create;
-(void) releaseBufferForFile:(NSString *) filePath;

@end

Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ -(void) load:(NSString*) filePath {
[self pause];
[self rewind];
}
audioSourcePlayer.volume = volume;
audioSourcePlayer.volume = mute ? 0.0f : volume;
audioSourcePlayer.numberOfLoops = numberOfLoops;
state = kLAS_Loaded;
}
Expand Down
60 changes: 60 additions & 0 deletions CocosDenshion/CDConfig.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
Copyright (c) 2010 Steve Oldmeadow

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

$Id$
*/
#define COCOSDENSHION_VERSION "Aphex.rc"


/**
If enabled code useful for debugging such as parameter check assertions will be performed.
If you experience any problems you should enable this and test your code with a debug build.
*/
//#define CD_DEBUG 1

/**
The total number of sounds/buffers that can be loaded assuming memory is sufficient
*/
//Number of buffers slots that will be initially created
#define CD_BUFFERS_START 64
//Number of buffers that will be added
#define CD_BUFFERS_INCREMENT 16

/**
If enabled, OpenAL code will use static buffers. When static buffers are used the audio
data is managed outside of OpenAL, this eliminates a memcpy operation which leads to
higher performance when loading sounds.

However, the downside is that when the audio data is freed you must
be certain that it is no longer being accessed otherwise your app will crash. Testing on OS 2.2.1
and 3.1.2 has shown that this may occur if a buffer is being used by a source with state = AL_PLAYING
when the buffer is deleted. If the data is freed too quickly after the source is stopped then
a crash will occur. The implemented workaround is that when static buffers are used the unloadBuffer code will wait for
any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any
performance gains that are achieved during loading.

Performance tests on a 1st gen iPod running OS 2.2.1 loading the CocosDenshionDemo sounds were ~0.14 seconds without
static buffers and ~0.12 seconds when using static buffers.

*/
//#define CD_USE_STATIC_BUFFERS 1


77 changes: 77 additions & 0 deletions CocosDenshion/CDOpenALSupport.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*

Disclaimer: IMPORTANT: This Apple software is supplied to you by
Apple Inc. ("Apple") in consideration of your agreement to the
following terms, and your use, installation, modification or
redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use,
install, modify or redistribute this Apple software.

In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc.
may be used to endorse or promote products derived from the Apple
Software without specific prior written permission from Apple. Except
as expressly stated in this notice, no other rights or licenses, express
or implied, are granted by Apple herein, including but not limited to
any patent rights that may be infringed by your derivative works or by
other works in which the Apple Software may be incorporated.

The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

Copyright (C) 2009 Apple Inc. All Rights Reserved.

$Id$
*/

/*
This file contains code from version 1.1 and 1.4 of MyOpenALSupport.h taken from Apple's oalTouch version.
The 1.4 version code is used for loading IMA4 files, however, this code causes very noticeable clicking
when used to load wave files that are looped so the 1.1 version code is used specifically for loading
wav files.
*/

#ifndef __CD_OPENAL_H
#define __CD_OPENAL_H

#ifdef __cplusplus
extern "C" {
#endif


#import <OpenAL/al.h>
#import <OpenAL/alc.h>
#import <CoreFoundation/CFURL.h>


//Taken from oalTouch MyOpenALSupport 1.1
void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);

#ifdef __cplusplus
}
#endif

#endif


File renamed without changes.
Loading