⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 soundengine.cpp

📁 在iPhone OS上使用用Objective-C语言开发的Demo程序
💻 CPP
📖 第 1 页 / 共 4 页
字号:
/*===== IMPORTANT =====This is sample code demonstrating API, technology or techniques in development.Although this sample code has been reviewed for technical accuracy, it is notfinal. Apple is supplying this information to help you plan for the adoption ofthe technologies and programming interfaces described herein. This informationis subject to change, and software implemented based on this sample code shouldbe tested with final operating system software and final documentation. Newerversions of this sample code may be provided with future seeds of the API ortechnology. For information about updates to this and other developerdocumentation, view the New & Updated sidebars in subsequent documentationseeds.=====================File: SoundEngine.cppAbstract: These functions play background music tracks, multiple sound effects,and support stereo panning with a low-latency response.Version: 1.6Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.("Apple") in consideration of your agreement to the following terms, and youruse, installation, modification or redistribution of this Apple softwareconstitutes 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 subjectto these terms, Apple grants you a personal, non-exclusive license, underApple's copyrights in this original Apple software (the "Apple Software"), touse, reproduce, modify and redistribute the Apple Software, with or withoutmodifications, in source and/or binary forms; provided that if you redistributethe Apple Software in its entirety and without modifications, you must retainthis notice and the following text and disclaimers in all such redistributionsof the Apple Software.Neither the name, trademarks, service marks or logos of Apple Inc. may be usedto endorse or promote products derived from the Apple Software without specificprior 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 yourderivative works or by other works in which the Apple Software may beincorporated.The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NOWARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIEDWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR INCOMBINATION WITH YOUR PRODUCTS.IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL ORCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTEGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/ORDISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OFCONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IFAPPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Copyright (C) 2008 Apple Inc. All Rights Reserved.*/#if !TARGET_IPHONE_SIMULATOR/*==================================================================================================	SoundEngine.cpp==================================================================================================*/#if !defined(__SoundEngine_cpp__)#define __SoundEngine_cpp__//==================================================================================================//	Includes//==================================================================================================//	System Includes#include <AudioToolbox/AudioToolbox.h>#include <CoreFoundation/CFURL.h>#include <OpenAL/al.h>#include <OpenAL/alc.h>#include <map>#include <vector>#include <pthread.h>#include <mach/mach.h>// Local Includes#include "SoundEngine.h"#define	AssertNoError(inMessage, inHandler)						\			if(result != noErr)									\			{													\				printf("%s: %d\n", inMessage, (int)result);		\				goto inHandler;									\			}			#define AssertNoOALError(inMessage, inHandler)					\			if((result = alGetError()) != AL_NO_ERROR)			\			{													\				printf("%s: %x\n", inMessage, (int)result);		\				goto inHandler;									\			}#define kNumberBuffers 3class OpenALObject;class BackgroundTrackMgr;static OpenALObject			*sOpenALObject = NULL;static BackgroundTrackMgr	*sBackgroundTrackMgr = NULL;static Float32				gMasterVolumeGain = 1.0;// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~typedef ALvoid	AL_APIENTRY	(*alBufferDataStaticProcPtr) (const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq);ALvoid  alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq){	static	alBufferDataStaticProcPtr	proc = NULL;        if (proc == NULL) {        proc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic");    }        if (proc)        proc(bid, format, data, size, freq);    return;}// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~typedef ALvoid	AL_APIENTRY	(*alcMacOSXMixerOutputRateProcPtr) (const ALdouble value);ALvoid  alcMacOSXMixerOutputRateProc(const ALdouble value){	static	alcMacOSXMixerOutputRateProcPtr	proc = NULL;        if (proc == NULL) {        proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate");    }        if (proc)        proc(value);    return;}#pragma mark ***** OpenALThread *****//==================================================================================================//	Threading functions//==================================================================================================class	OpenALThread{// returns the thread's priority as it was last set by the API#define OpenALThread_SET_PRIORITY				0// returns the thread's priority as it was last scheduled by the Kernel#define OpenALThread_SCHEDULED_PRIORITY		1//	Typespublic:	typedef void*			(*ThreadRoutine)(void* inParameter);//	Constantspublic:	enum	{							kMinThreadPriority = 1,							kMaxThreadPriority = 63,							kDefaultThreadPriority = 31	};//	Construction/Destructionpublic:	OpenALThread(ThreadRoutine inThreadRoutine, void* inParameter)		:	mPThread(0),			mSpawningThreadPriority(getScheduledPriority(pthread_self(), OpenALThread_SET_PRIORITY)),			mThreadRoutine(inThreadRoutine),			mThreadParameter(inParameter),			mPriority(kDefaultThreadPriority),			mFixedPriority(false),			mAutoDelete(true) { }	~OpenALThread() { }//	Properties	bool IsRunning() const { return 0 != mPThread; }	void SetAutoDelete(bool b) { mAutoDelete = b; }	void SetPriority(UInt32 inPriority, bool inFixedPriority)	{		OSStatus result = noErr;		mPriority = inPriority;		mFixedPriority = inFixedPriority;		if(mPThread != 0)		{			if (mFixedPriority)			{				thread_extended_policy_data_t		theFixedPolicy;				theFixedPolicy.timeshare = false;	// set to true for a non-fixed thread				result  = thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT);				if (result) {					printf("OpenALThread::SetPriority: failed to set the fixed-priority policy");					return;				}			}			// We keep a reference to the spawning thread's priority around (initialized in the constructor), 			// and set the importance of the child thread relative to the spawning thread's priority.			thread_precedence_policy_data_t		thePrecedencePolicy;						thePrecedencePolicy.importance = mPriority - mSpawningThreadPriority;			result =thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT);			if (result) {				printf("OpenALThread::SetPriority: failed to set the precedence policy");				return;			}		} 	}//	Actions	void Start()	{		if(mPThread != 0)		{			printf("OpenALThread::Start: can't start because the thread is already running\n");			return;		}		OSStatus			result;		pthread_attr_t		theThreadAttributes;				result = pthread_attr_init(&theThreadAttributes);			AssertNoError("Error initializing thread", end);				result = pthread_attr_setdetachstate(&theThreadAttributes, PTHREAD_CREATE_DETACHED);			AssertNoError("Error setting thread detach state", end);						result = pthread_create(&mPThread, &theThreadAttributes, (ThreadRoutine)OpenALThread::Entry, this);			AssertNoError("Error creating thread", end);				pthread_attr_destroy(&theThreadAttributes);			AssertNoError("Error destroying thread attributes", end);end:		return;	}//	Implementationprotected:	static void* Entry(OpenALThread* inOpenALThread)	{		void* theAnswer = NULL;		inOpenALThread->SetPriority(inOpenALThread->mPriority, inOpenALThread->mFixedPriority);		if(inOpenALThread->mThreadRoutine != NULL)		{			theAnswer = inOpenALThread->mThreadRoutine(inOpenALThread->mThreadParameter);		}		inOpenALThread->mPThread = 0;		if (inOpenALThread->mAutoDelete)			delete inOpenALThread;		return theAnswer;	}	static UInt32 getScheduledPriority(pthread_t inThread, int inPriorityKind)	{		thread_basic_info_data_t			threadInfo;		policy_info_data_t					thePolicyInfo;		unsigned int						count;		if (inThread == NULL)			return 0;				// get basic info		count = THREAD_BASIC_INFO_COUNT;		thread_info (pthread_mach_thread_np (inThread), THREAD_BASIC_INFO, (thread_info_t)&threadInfo, &count);				switch (threadInfo.policy) {			case POLICY_TIMESHARE:				count = POLICY_TIMESHARE_INFO_COUNT;				thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_TIMESHARE_INFO, (thread_info_t)&(thePolicyInfo.ts), &count);				if (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) {					return thePolicyInfo.ts.cur_priority;				}				return thePolicyInfo.ts.base_priority;				break;							case POLICY_FIFO:				count = POLICY_FIFO_INFO_COUNT;				thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_FIFO_INFO, (thread_info_t)&(thePolicyInfo.fifo), &count);				if ( (thePolicyInfo.fifo.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) {					return thePolicyInfo.fifo.depress_priority;				}				return thePolicyInfo.fifo.base_priority;				break;							case POLICY_RR:				count = POLICY_RR_INFO_COUNT;				thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_RR_INFO, (thread_info_t)&(thePolicyInfo.rr), &count);				if ( (thePolicyInfo.rr.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) {					return thePolicyInfo.rr.depress_priority;				}				return thePolicyInfo.rr.base_priority;				break;		}				return 0;	}	pthread_t				mPThread;    UInt32					mSpawningThreadPriority;	ThreadRoutine			mThreadRoutine;	void*					mThreadParameter;	SInt32					mPriority;    bool					mFixedPriority;	bool					mAutoDelete;		// delete self when thread terminates};//==================================================================================================//	Helper functions//==================================================================================================OSStatus OpenFile(const char *inFilePath, AudioFileID &outAFID){		CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), false);	if (theURL == NULL)		return kSoundEngineErrFileNotFound;#if TARGET_OS_IPHONE	OSStatus result = AudioFileOpenURL(theURL, kAudioFileReadPermission, 0, &outAFID);#else	OSStatus result = AudioFileOpenURL(theURL, fsRdPerm, 0, &outAFID);#endif	CFRelease(theURL);		AssertNoError("Error opening file", end);	end:		return result;}OSStatus LoadFileDataInfo(const char *inFilePath, AudioFileID &outAFID, AudioStreamBasicDescription &outFormat, UInt64 &outDataSize){	UInt32 thePropSize = sizeof(outFormat);					OSStatus result = OpenFile(inFilePath, outAFID);		AssertNoError("Error opening file", end);	result = AudioFileGetProperty(outAFID, kAudioFilePropertyDataFormat, &thePropSize, &outFormat);		AssertNoError("Error getting file format", end);		thePropSize = sizeof(UInt64);	result = AudioFileGetProperty(outAFID, kAudioFilePropertyAudioDataByteCount, &thePropSize, &outDataSize);		AssertNoError("Error getting file data size", end);end:	return result;}void CalculateBytesForTime (AudioStreamBasicDescription & inDesc, UInt32 inMaxPacketSize, Float64 inSeconds, UInt32 *outBufferSize, UInt32 *outNumPackets){	static const UInt32 maxBufferSize = 0x10000; // limit size to 64K	static const UInt32 minBufferSize = 0x4000; // limit size to 16K	if (inDesc.mFramesPerPacket) {		Float64 numPacketsForTime = inDesc.mSampleRate / inDesc.mFramesPerPacket * inSeconds;		*outBufferSize = numPacketsForTime * inMaxPacketSize;	} else {		// if frames per packet is zero, then the codec has no predictable packet == time		// so we can't tailor this (we don't know how many Packets represent a time period		// we'll just return a default buffer size		*outBufferSize = maxBufferSize > inMaxPacketSize ? maxBufferSize : inMaxPacketSize;	}			// we're going to limit our size to our default	if (*outBufferSize > maxBufferSize && *outBufferSize > inMaxPacketSize)		*outBufferSize = maxBufferSize;	else {		// also make sure we're not too small - we don't want to go the disk for too small chunks		if (*outBufferSize < minBufferSize)			*outBufferSize = minBufferSize;	}	*outNumPackets = *outBufferSize / inMaxPacketSize;}static Boolean MatchFormatFlags(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y){	UInt32 xFlags = x.mFormatFlags;	UInt32 yFlags = y.mFormatFlags;		// match wildcards	if (x.mFormatID == 0 || y.mFormatID == 0 || xFlags == 0 || yFlags == 0) 		return true;		if (x.mFormatID == kAudioFormatLinearPCM)	{		 				// knock off the all clear flag		xFlags = xFlags & ~kAudioFormatFlagsAreAllClear;		yFlags = yFlags & ~kAudioFormatFlagsAreAllClear;			// if both kAudioFormatFlagIsPacked bits are set, then we don't care about the kAudioFormatFlagIsAlignedHigh bit.		if (xFlags & yFlags & kAudioFormatFlagIsPacked) {			xFlags = xFlags & ~kAudioFormatFlagIsAlignedHigh;			yFlags = yFlags & ~kAudioFormatFlagIsAlignedHigh;		}				// if both kAudioFormatFlagIsFloat bits are set, then we don't care about the kAudioFormatFlagIsSignedInteger bit.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -