OpenAl SoundManager, dll version


Goals
Simple sound manager using OpenAL (http://www.OpenAL.org).
Nearly no Ogre code was used to be as universal as possible (only exception OgreVector3.h and OgreQuaternion.h)

If you want a more advanced manager, see OpenAL++ (http://alpp.sourceforge.net/)

Please, use this forum thread to discuss problems, suggestions, etc.

TODO
Make the au format readable
make functions that call the EAX functions !
Compiling
Download and install the OpenAL library and DLL.
Download and compile the OGG-Vorbis SDK take the most recent libvorbis archive 
You 'need' to compile or have the ogg dll (vorbisfile.dll, ogg.dll,vorbisenc.dll, vorbis.dll), setting the Code Generation to "Multithread DLL" with visual Studio.
Include the "OpenAl_library/include" containing the directories AL and ALUT.
Link to : ALut.lib and OpenAL32.lib. The order is important.
Link to : vorbis.lib ogg.lib vorbisenc.lib vorbisfile.lib
Adjust for your need the #define and #include of libOpenAl.h
You should replace all "printf" by your own version log message.
With CodeBlocks there is one warning with the last OpenALSDK 1

Code:
  1. //Main.cpp   
  2. #include <iostream>   
  3.  #include "libOpenAl.h"   
  4.     
  5.  int main()   
  6.  {   
  7.    std::cout << "Simple Sound Manager test application !" << std::endl;   
  8.     
  9.    SoundManager* soundMgr = SoundManager::createManager();   
  10.     
  11.    std::cout << soundMgr->listAvailableDevices();   
  12.     
  13.    soundMgr->init();   
  14.     
  15.    // careful : should not be used it doesn't use the resource limitation   
  16.    //soundMgr->testSound( "test.wav" );   
  17.     
  18.    soundMgr->setAudioPath( (char*) ".//" );   
  19.     
  20.    unsigned int audioId;   
  21.     
  22.    // We loop to be able to test the pause function   
  23.    soundMgr->loadAudio( "test.wav", &audioId, true);   
  24.     
  25.  /*     
  26.     // Set our LISTENER Location (i.e. the ears)  
  27.     // The listener is what hears the sounds emitted by audio sources.  
  28.     // Note: you only have ONE set of ears - i.e. there is only ONE listener.  
  29.     soundMgr->setListenerPosition( mPlayerSceneNode->getWorldPosition(),  
  30.         Ogre::Vector3::ZERO, mPlayerSceneNode->getOrientation() );  
  31.    
  32.     // Set the Audio SOURCE location/position AND by default PLAY the audio.  
  33.     // Note how we reference the correct audio source by using 'mAudioSource'.  
  34.    
  35.     soundMgr->setSound( audioId, mSomeObjectSceneNode->getWorldPosition(),  
  36.         Ogre::Vector3::ZERO, Ogre::Vector3::ZERO, 1000.0f, true, true, 1.0f );  
  37.  */  
  38.     
  39.     // Play an Audio source - force a restart from the begining of the buffer.   
  40.     // That means, re-play the media file from the begining.   
  41.     soundMgr->playAudio( audioId, true );   
  42.     
  43.     printf("Audio playing.  Type Enter./n");   
  44.     getchar(); // To hear the sound until the end.   
  45.     
  46.     soundMgr->pauseAudio( audioId );   
  47.     
  48.     printf("Audio paused.  Type Enter./n");   
  49.     getchar();   
  50.     
  51.  //   soundMgr->resumeAudio( audioId );   
  52.     soundMgr->resumeAllAudio( );   
  53.     
  54.     printf("Audio playing. Type Enter/n");   
  55.     getchar();   
  56.     
  57.     // Force an audio source to stop playing.   
  58.     soundMgr->stopAudio( audioId );   
  59.     
  60.    // Release an audio source when we are done with it.   
  61.    // This isn't required if you destruct the AudioEngine - as it cleans itself up.   
  62.    // But, you *SHOULD* do this when, for example, your SceneObject is no longer   
  63.    // in the scene for some reason. In other words, if you don't need this source   
  64.    // anymore then free up the resource. Remember, you are limited in audio sources.   
  65.    soundMgr->releaseAudio( audioId );   
  66.     
  67.    delete soundMgr;   
  68.     
  69.    return 0;   
  70.  }  

 

Code:
  1. /libOpenAl.h   
  2.   
  3. /**  
  4.  *  libOpenAl.h  
  5.  *  
  6.  *  Original Code : Van Stokes, Jr. (http://www.EvilMasterMindsInc.com) - Aug 05  
  7.  *  Modified Code : Steven Gay - mec3@bluewin.ch - Septembre 2005 - Jan 06  
  8.  *  Dll version   : Griffo Jean-Baptiste , crashy@antharia.org - Jan 06  
  9.  *  
  10.  *                    Partial Documentation  
  11.  *                    =====================  
  12.  *  
  13.  *  Very simple SoundManager using OpenAl.   
  14.  *  
  15.  *  For a more complete one, you should see :  
  16.  *  OpenAL++ http://alpp.sourceforge.net/  
  17.  *  
  18.  ****************************************************************************  
  19.  *  COMPILE  
  20.  *  
  21.  *  - Don't forget to link to : ALut.lib and OpenAL32.lib.  
  22.  *    The order is important.  
  23.  *  
  24.  *  - With CodeBlocks there is one warning I didn't resolve :  
  25.  *     "Warning: .drectve `/DEFAULTLIB:"uuid.lib" /DEFAULTLIB:"uuid.lib" ' unrecognized"  
  26.  *  
  27.  ****************************************************************************  
  28.  *  USAGE  
  29.  *  
  30.  * 1. Create the object from the class with createManager()  
  31.  *   
  32.  * 2. Call the init() function  
  33.  *  
  34.  * 3. Call the loadDefaultSounds() function to PRE-LOAD audio into the buffers.  
  35.  *    This is optional. Review the function to make changes that you need.  
  36.  *  
  37.  * 4. Set the Listener Location by calling setListenerPosition() function  
  38.  *    continually call this as your Listener (camera) position changes!  
  39.  *  
  40.  * 5. For each object that emits sound, call the loadSound() function.  
  41.  *    CAREFUL : The filename must be unique.  
  42.  *  
  43.  * 6. Optional : For each object you can set the all the parameters of the  
  44.  *    sound with setSound() or only the position, velocity and direction with  
  45.  *    setSoundPosition().  
  46.  *  
  47.  * 7. Call the playAudioSource() to play the sound at some event.  
  48.  *    This function will play the sound and then stop. It will NOT repeat playing.  
  49.  *    Use stopAudioSource() to stop a sound from playing if its still playing   
  50.  *  
  51.  * 8. Call pauseAudio() or pauseAllAudio() to pause one or all sound(s).  
  52.  *    Call resumeAudio() or resumeAllAudio() to resume one or all paused sound(s).  
  53.  *  
  54.  * 9. When your object is done emitting sounds (when out of range for example)  
  55.  *    call releaseAudioSource().  
  56.  *    It is important to release your source when you are no longer going to  
  57.  *    need it because you are limited in the number of sources you can have.  
  58.  *  
  59.  * 10. If your objects moves (other than the listener/camera) then  
  60.  *    continually update the objects position by calling setSourcePosition().  
  61.  *  
  62.  ******************************************************************************  
  63.  *   
  64.  * Additional informations :  
  65.  *  
  66.  * Ogg Vorbis - http://www.xiph.org/downloads/  
  67.  *            - http://www.illiminable.com/ogg/  
  68.  * Flac       - http://flac.sourceforge.net/features.html  
  69.  * Theora     - http://www.theora.org/  
  70.  *  
  71.  *  
  72.  ******************************************************************************  
  73.  *  
  74.  * TODO  
  75.  *  
  76.  * loadOGG()  
  77.  * alSourcePause()  
  78.  *  
  79.  * Use the EAX functions !  
  80.  *  
  81.  ******************************************************************************/  
  82.     
  83.     
  84.  #ifndef __SOUNDMANAGER_H__   
  85.  #define __SOUNDMANAGER_H__   
  86.     
  87.     
  88.     
  89.  #if  defined(USE_OPAL_SOUND_MGR)   
  90.          #if !defined(__MINGW32__) && !defined(__CYGWIN__)   
  91.               #define OPAL_SOUND_MGR __declspec(dllimport)   
  92.          #else   
  93.                #define OPAL_SOUND_MGR   
  94.          #endif   
  95.  #elif defined(CMP_OPAL_SOUND_MGR)   
  96.          #define OPAL_SOUND_MGR __declspec(dllexport)   
  97.  #else   
  98.          #define OPAL_SOUND_MGR   
  99.  #endif    
  100.     
  101.  #ifdef _WIN32   
  102.  #include <io.h>   
  103.  #include <fcntl.h>   
  104.  #endif   
  105.     
  106.  #include <stdio.h>   
  107.  #include <string>   
  108.     
  109.  // Comment this line if you don't have the EAX 2.0 SDK installed   
  110.  //#define _USEEAX   
  111.     
  112.  #ifdef _USEEAX   
  113.     #include "eax.h"   
  114.  #endif   
  115.     
  116.  // OpenAl version 1.0   
  117.  // #include <al/alctypes.h>   
  118.  // #include <al/altypes.h>   
  119.  // #include <al/alc.h>   
  120.  // #include <al/al.h>   
  121.  // #include <alut/alut.h>   
  122.  // OpenAl version 1.1   
  123.  #include <al.h>   
  124.  #include <alc.h>   
  125.  #include <alut.h>   
  126.     
  127.  #include "codec.h"   
  128.     
  129.  #include "vorbisfile.h"   
  130.     
  131.  // Modify this as you need.    
  132.  #ifdef OGRE    
  133.    #include "OgreVector3.h"    
  134.    #include "OgreQuaternion.h"    
  135.    using namespace Ogre;    
  136.  #else    
  137.    #include "Vector3.h"    
  138.    using namespace gameengine::utilities;    
  139.  #endif   
  140.     
  141.     
  142.     
  143.  // Used to store sound filenames   
  144.  #define MAX_FILENAME_LENGTH 40   
  145.     
  146.  class OPAL_SOUND_MGR SoundManager   
  147.  {   
  148.   private:   
  149.        // EAX related   
  150.        bool isEAXPresent;   
  151.  #ifdef _USEEAX   
  152.        // EAX 2.0 GUIDs   
  153.        const GUID DSPROPSETID_EAX20_ListenerProperties   
  154.            = { 0x306a6a8, 0xb224, 0x11d2, { 0x99, 0xe5, 0x0, 0x0, 0xe8, 0xd8, 0xc7, 0x22 } };   
  155.     
  156.        const GUID DSPROPSETID_EAX20_BufferProperties   
  157.            = { 0x306a6a7, 0xb224, 0x11d2, {0x99, 0xe5, 0x0, 0x0, 0xe8, 0xd8, 0xc7, 0x22 } };   
  158.     
  159.        EAXSet eaxSet; // EAXSet function, retrieved if EAX Extension is supported   
  160.        EAXGet eaxGet; // EAXGet function, retrieved if EAX Extension is supported   
  161.  #endif // _USEEAX   
  162.     
  163.        bool isInitialised;   
  164.        ALCdevice* mSoundDevice;   
  165.        ALCcontext* mSoundContext;   
  166.     
  167.        std::string mAudioPath;   
  168.     
  169.        bool isSoundOn;   
  170.     
  171.        ALfloat position[3];   
  172.        ALfloat velocity[3];   
  173.        ALfloat orientation[6];   
  174.     
  175.        // Needed because of hardware limitation   
  176.        // Audio sources   
  177.        unsigned const short MAX_AUDIO_SOURCES;   
  178.        unsigned int mAudioSourcesInUseCount;   
  179.        unsigned int* mAudioSources;   
  180.        bool         *mAudioSourceInUse;   
  181.     
  182.        // Audio buffers   
  183.        unsigned const short int MAX_AUDIO_BUFFERS;   
  184.        unsigned int mAudioBuffersInUseCount;   
  185.        unsigned int* mAudioBuffers;   
  186.        bool         *mAudioBufferInUse;   
  187.        std::map<int,std::string, std::less<int> > mAudioBufferFileName;   
  188.     
  189.        // Function to check if the soundFile is already loaded into a buffer   
  190.        int locateAudioBuffer( std::string filename );   
  191.        int loadAudioInToSystem( std::string filename );   
  192.        bool loadWAV( std::string filename, ALuint pDestAudioBuffer );   
  193.        bool loadOGG( std::string filename, ALuint pDestAudioBuffer );   
  194.        bool loadOGGFile(std::string fileName, std::vector<char> &buffer,    
  195.  ALenum &format,ALsizei &freq);   
  196.        // TODO bool loadAU( std::string filename, ALuint pDestAudioBuffer );   
  197.     
  198.        // Ogg Vorbis extension   
  199.        bool bOggExtensionPresent;   
  200.     
  201.    public:   
  202.        static SoundManager* mSoundManager;   
  203.       // SoundManager(void);   
  204.        SoundManager( int max_buffers, int max_sources );   
  205.        virtual ~SoundManager( void );   
  206.        void SoundManager::selfDestruct( void );   
  207.        static SoundManager* createManager( void );   
  208.        static SoundManager* createManager( int,int );   
  209.        static SoundManager* getSingletonPtr( void ) { return mSoundManager; };   
  210.     
  211.        bool init( void );   
  212.        bool getIsSoundOn( void ) { return isSoundOn; };   
  213.        void setAudioPath( char* path ) { mAudioPath = std::string( path ); };   
  214.     
  215.        bool checkALError( void );   
  216.        bool checkALError( std::string pMsg );   
  217.     
  218.        /** See http://www.openal.org/windows_enumeration.html for installing other  
  219.        *   devices. You should at least have "Generic Hardware".  
  220.        */  
  221.        std::string listAvailableDevices( void );   
  222.     
  223.        // careful : testSound should not be used it doesn't use the resource limitation   
  224.        void testSound( const char* wavFile );   
  225.     
  226.        // Aquire an Audio Source   
  227.        // filename = pass in the sound file to play for this source (ex. "myfile.wav")   
  228.        // audioId   = returns the AudioSource identifier you will need for the PlayAudioSource();   
  229.        bool loadAudio( std::string filename, unsigned int *audioId, bool loop );   
  230.        bool releaseAudio( unsigned int audioID );   
  231.     
  232.        // deprecated   
  233.        bool aquireAudioSource( char* file, unsigned int *audioId )   
  234.            { return loadAudio( std::string(file), audioId, false ); };   
  235.     
  236.        // Returns true if the audio is started from the beginning   
  237.        // false if error or if already playing   
  238.        bool playAudio( unsigned int audioId, bool forceRestart );   
  239.        bool stopAudio( unsigned int audioID );   
  240.        bool stopAllAudio( void );   
  241.     
  242.        bool pauseAudio( unsigned int audioID );   
  243.        bool pauseAllAudio( void );   
  244.        bool resumeAudio( unsigned int audioID );   
  245.        bool resumeAllAudio( void );   
  246.     
  247.        bool setSoundPosition( unsigned int audioID, Vector3 position );   
  248.     
  249.        bool setSoundPosition( unsigned int audioID, Vector3 position,   
  250.            Vector3 velocity, Vector3 direction );   
  251.     
  252.        bool setSound( unsigned int audioID, Vector3 position,   
  253.            Vector3 velocity, Vector3 direction, float maxDistance,   
  254.            bool playNow, bool forceRestart, float minGain );   
  255.     
  256.        bool setListenerPosition( Vector3 position, Vector3 velocity,   
  257.            Quaternion orientation );   
  258.     
  259.        bool isOggExtensionPresent( void );   
  260.     
  261.        bool setGain(unsigned int,float gain);   
  262.     
  263.        /**  
  264.         * Preload audio files into the system.  
  265.         * Not obligatory, the files can also be loaded on the fly.  
  266.         */  
  267.        bool loadDefaultSounds( std::string filename );   
  268.        // Function to trim the trailing crap from a string.   
  269.        void trimTrailingSpace( char *s );   
  270.     
  271.  };   
  272.     
  273.  #endif /*__SOUNDMANAGER_H__*/  
Code:
  1. //libOpenAl.cpp   
  2.   
  3.   
  4. #define CMP_OPAL_SOUND_MGR   
  5.     
  6.  #include "libOpenAl.h"   
  7.     
  8.  /**  
  9.  *  libOpenAl.cpp  
  10.  *  
  11.  *  Original Code : Van Stokes, Jr. (http://www.EvilMasterMindsInc.com) - Aug 05  
  12.  *  Modified Code : Steven Gay - mec3@bluewin.ch - Septembre 2005  
  13.  *  Dll version   : Griffo Jean-Baptiste , crashy@antharia.org - Jan 06  
  14.  */  
  15.     
  16.  SoundManager* SoundManager::mSoundManager = NULL;   
  17.     
  18.  /****************************************************************************/  
  19.  OPAL_SOUND_MGR SoundManager::SoundManager( int max_buffers=64, int max_sources =16 )   
  20.  : MAX_AUDIO_BUFFERS(max_buffers),MAX_AUDIO_SOURCES(max_sources)   
  21.  {   
  22.     
  23.    mSoundManager = this;   
  24.     
  25.    isInitialised = false;   
  26.    isSoundOn = false;   
  27.    mSoundDevice = 0;   
  28.    mSoundContext = 0;   
  29.     
  30.    mAudioPath = "";   
  31.     
  32.    // EAX related   
  33.    isEAXPresent = false;   
  34.     
  35.    // Initial position of the listener   
  36.    position[0] = 0.0;   
  37.    position[1] = 0.0;   
  38.    position[2] = 0.0;   
  39.     
  40.    // Initial velocity of the listener   
  41.    velocity[0] = 0.0;   
  42.    velocity[1] = 0.0;   
  43.    velocity[2] = 0.0;   
  44.     
  45.    // Initial orientation of the listener = direction + direction up   
  46.    orientation[0] = 0.0;   
  47.    orientation[1] = 0.0;   
  48.    orientation[2] = -1.0;   
  49.    orientation[3] = 0.0;   
  50.    orientation[4] = 1.0;   
  51.    orientation[5] = 0.0;   
  52.     
  53.    // Needed because of hardware limitation   
  54.    mAudioBuffersInUseCount = 0;   
  55.    mAudioSourcesInUseCount = 0;   
  56.    mAudioSources=new unsigned int[MAX_AUDIO_SOURCES];   
  57.    mAudioSourceInUse=new bool[MAX_AUDIO_SOURCES];   
  58.     
  59.    for ( int i=0; i < MAX_AUDIO_SOURCES; i++ )   
  60.    {   
  61.       mAudioSources[i] = 0;   
  62.       mAudioSourceInUse[i] = false;   
  63.    }   
  64.     
  65.     mAudioBuffers=new unsigned int[MAX_AUDIO_BUFFERS];   
  66.     mAudioBufferInUse=new bool[MAX_AUDIO_BUFFERS];   
  67.    for ( int i=0; i < MAX_AUDIO_BUFFERS; i++ )   
  68.    {   
  69.       mAudioBuffers[i] = 0;   
  70.     
  71.       mAudioBufferInUse[i] = false;   
  72.    }   
  73.     
  74.   printf("SoudManager Created./n");   
  75.  }   
  76.     
  77.  /****************************************************************************/  
  78.  OPAL_SOUND_MGR SoundManager::~SoundManager( void )   
  79.  {   
  80.   // Delete the sources and buffers   
  81.   alDeleteSources( MAX_AUDIO_SOURCES, mAudioSources );   
  82.   alDeleteBuffers( MAX_AUDIO_BUFFERS, mAudioBuffers );   
  83.     
  84.    // Destroy the sound context and device   
  85.    mSoundContext = alcGetCurrentContext();   
  86.    mSoundDevice = alcGetContextsDevice( mSoundContext );   
  87.    alcMakeContextCurrent( NULL );   
  88.    alcDestroyContext( mSoundContext );   
  89.    if ( mSoundDevice)   
  90.        alcCloseDevice( mSoundDevice );   
  91.     
  92.    alutExit();   
  93.     
  94.   printf("SoudManager Destroyed./n");   
  95.   mAudioBufferFileName.clear();   
  96.   delete mAudioSources;   
  97.   delete mAudioSourceInUse;   
  98.  }   
  99.     
  100.  /****************************************************************************/  
  101.  OPAL_SOUND_MGR void SoundManager::selfDestruct( void )   
  102.  {   
  103.   if ( getSingletonPtr() ) delete getSingletonPtr();   
  104.  }   
  105.     
  106.  /****************************************************************************/  
  107.  OPAL_SOUND_MGR SoundManager* SoundManager::createManager( void )   
  108.  {   
  109.   if (mSoundManager == 0)   
  110.        mSoundManager = new SoundManager();   
  111.    return mSoundManager;   
  112.  }   
  113.  OPAL_SOUND_MGR SoundManager* SoundManager::createManager( int max_sources, int max_buffers )   
  114.  {   
  115.   if (mSoundManager == 0)   
  116.        mSoundManager = new SoundManager(max_sources,max_buffers);   
  117.    return mSoundManager;   
  118.  }   
  119.  /****************************************************************************/  
  120.  OPAL_SOUND_MGR bool SoundManager::init( void )   
  121.  {   
  122.   // It's an error to initialise twice OpenAl   
  123.   if ( isInitialised ) return true;   
  124.     
  125.   // Open an audio device   
  126.   mSoundDevice = alcOpenDevice( NULL ); // TODO ((ALubyte*) "DirectSound3D");   
  127.   // mSoundDevice = alcOpenDevice( "DirectSound3D" );   
  128.     
  129.   // Check for errors   
  130.   if ( !mSoundDevice )   
  131.   {   
  132.      printf( "SoundManager::init error : No sound device./n");   
  133.      return false;   
  134.   }   
  135.     
  136.   mSoundContext = alcCreateContext( mSoundDevice, NULL );   
  137.  //   if ( checkAlError() || !mSoundContext ) // TODO seems not to work! why ?   
  138.   if ( !mSoundContext )   
  139.   {   
  140.      printf( "SoundManager::init error : No sound context./n");   
  141.      return false;   
  142.   }   
  143.     
  144.   // Make the context current and active   
  145.   alcMakeContextCurrent( mSoundContext );   
  146.   if ( checkALError( "Init()" ) )   
  147.   {   
  148.      printf( "SoundManager::init error : could not make sound context current and active./n");   
  149.      return false;   
  150.   }   
  151.     
  152.   // Check for EAX 2.0 support and   
  153.   // Retrieves function entry addresses to API ARB extensions, in this case,   
  154.   // for the EAX extension. See Appendix 1 (Extensions) of   
  155.   // http://www.openal.org/openal_webstf/specs/OpenAL1-1Spec_html/al11spec7.html   
  156.   //   
  157.   // TODO EAX fct not used anywhere in the code ... !!!   
  158.   isEAXPresent = alIsExtensionPresent( "EAX2.0" );   
  159.   if ( isEAXPresent )   
  160.   {   
  161.      printf( "EAX 2.0 Extension available/n" );   
  162.     
  163.  #ifdef _USEEAX   
  164.        eaxSet = (EAXSet) alGetProcAddress( "EAXSet" );   
  165.        if ( eaxSet == NULL )   
  166.            isEAXPresent = false;   
  167.     
  168.        eaxGet = (EAXGet) alGetProcAddress( "EAXGet" );   
  169.        if ( eaxGet == NULL )   
  170.            isEAXPresent = false;   
  171.     
  172.        if ( !isEAXPresent )   
  173.            checkALError( "Failed to get the EAX extension functions adresses./n" );   
  174.  #else   
  175.        isEAXPresent = false;   
  176.        printf( "... but not used./n" );   
  177.  #endif // _USEEAX   
  178.     
  179.   }   
  180.     
  181.   // Test if Ogg Vorbis extension is present   
  182.   isOggExtensionPresent();   
  183.     
  184.   // Create the Audio Buffers   
  185.   alGenBuffers( MAX_AUDIO_BUFFERS, mAudioBuffers );   
  186.   if (checkALError("init::alGenBuffers:") )   
  187.        return false;   
  188.     
  189.   // Generate Sources   
  190.   alGenSources( MAX_AUDIO_SOURCES, mAudioSources );   
  191.   if (checkALError( "init::alGenSources :") )   
  192.        return false;   
  193.     
  194.     
  195.   // Setup the initial listener parameters   
  196.   // -> location   
  197.   alListenerfv( AL_POSITION, position );   
  198.     
  199.   // -> velocity   
  200.   alListenerfv( AL_VELOCITY, velocity );   
  201.     
  202.   // -> orientation   
  203.   alListenerfv( AL_ORIENTATION, orientation );   
  204.     
  205.   // Gain   
  206.   alListenerf( AL_GAIN, 1.0 );   
  207.     
  208.   // Initialise Doppler   
  209.   alDopplerFactor( 1.0 ); // 1.2 = exaggerate the pitch shift by 20%   
  210.   alDopplerVelocity( 343.0f ); // m/s this may need to be scaled at some point   
  211.     
  212.   // Ok   
  213.   isInitialised = true;   
  214.   isSoundOn = true;   
  215.     
  216.   printf( "SoundManager initialised./n/n");   
  217.     
  218.   return true;   
  219.  }   
  220.     
  221.  /****************************************************************************/  
  222.  OPAL_SOUND_MGR bool SoundManager::checkALError( void )   
  223.  {   
  224.   ALenum errCode;   
  225.   if ( ( errCode = alGetError() ) != AL_NO_ERROR )   
  226.   {   
  227.      std::string err = "ERROR SoundManager:: ";   
  228.      err += (char*) alGetString( errCode );   
  229.     
  230.      printf( "%s/n", err.c_str());   
  231.      return true;   
  232.   }   
  233.   return false;   
  234.  }   
  235.     
  236.  /****************************************************************************/  
  237.  OPAL_SOUND_MGR std::string SoundManager::listAvailableDevices( void )   
  238.  {   
  239.   std::string str = "Sound Devices available : ";   
  240.     
  241.   if ( alcIsExtensionPresent( NULL, "ALC_ENUMERATION_EXT" ) == AL_TRUE )   
  242.   {   
  243.        str = "List of Devices : ";   
  244.        str += (char*) alcGetString( NULL, ALC_DEVICE_SPECIFIER );   
  245.        str += "/n";   
  246.   }   
  247.   else  
  248.        str += " ... eunmeration error./n";   
  249.     
  250.    return str;   
  251.  }   
  252.     
  253.  /****************************************************************************/  
  254.  OPAL_SOUND_MGR bool SoundManager::checkALError( std::string pMsg )   
  255.  {   
  256.   ALenum error = 0;   
  257.     
  258.    if ( (error = alGetError()) == AL_NO_ERROR )   
  259.    return false;   
  260.     
  261.   char mStr[256];   
  262.   switch ( error )   
  263.   {   
  264.        case AL_INVALID_NAME:   
  265.            sprintf(mStr,"ERROR SoundManager::%s Invalid Name", pMsg.c_str());   
  266.            break;   
  267.        case AL_INVALID_ENUM:   
  268.            sprintf(mStr,"ERROR SoundManager::%s Invalid Enum", pMsg.c_str());   
  269.            break;   
  270.        case AL_INVALID_VALUE:   
  271.            sprintf(mStr,"ERROR SoundManager::%s Invalid Value", pMsg.c_str());   
  272.            break;   
  273.        case AL_INVALID_OPERATION:   
  274.            sprintf(mStr,"ERROR SoundManager::%s Invalid Operation", pMsg.c_str());   
  275.            break;   
  276.        case AL_OUT_OF_MEMORY:   
  277.            sprintf(mStr,"ERROR SoundManager::%s Out Of Memory", pMsg.c_str());   
  278.            break;   
  279.        default:   
  280.            sprintf(mStr,"ERROR SoundManager::%s Unknown error (%i) case in testALError()",   
  281.   pMsg.c_str(), error);   
  282.            break;   
  283.   };   
  284.     
  285.   printf( "%s/n", mStr );   
  286.     
  287.   return true;   
  288.  }   
  289.     
  290.  /*****************************************************************************/  
  291.  OPAL_SOUND_MGR void SoundManager::testSound( const char* wavFile )   
  292.  {   
  293.   ALuint buffer;   
  294.   ALuint source;   
  295.   ALenum format;   
  296.   ALsizei size;   
  297.   ALvoid* data;   
  298.   ALsizei freq;   
  299.   ALboolean loop;   
  300.   alGenBuffers( 1, &buffer );   
  301.   if ( checkALError( "testSound()" ) )   
  302.       return;   
  303.     
  304.   // This is the same for alutLoadWAVMemory   
  305.  #ifndef MACINTOSH_AL   
  306.   alutLoadWAVFile( (ALbyte*) wavFile, &format, &data, &size, &freq, &loop );   
  307.  #else   
  308.   alutLoadWAVFile( (ALbyte*) wavFile, &format, &data, &size, &freq );   
  309.  #endif   
  310.     
  311.   alBufferData( buffer, format, data, size, freq );   
  312.     
  313.   alutUnloadWAV( format, data, size, freq );   
  314.   alGenSources( 1, &source );   
  315.   alSourcei( source, AL_BUFFER, buffer );   
  316.   alSourcef( source, AL_PITCH, 1.0f );   
  317.   alSourcef( source, AL_GAIN, 1.0f );   
  318.     
  319.  #ifndef MACINTOSH_AL   
  320.   alSourcei( source, AL_LOOPING, loop );   
  321.  #else   
  322.   alSourcei( source, AL_LOOPING, false ); // TODO ! But how to get from file?   
  323.  #endif   
  324.     
  325.   alSourcePlay( source );   
  326.     
  327.   //Or else we risk to destroy the manager too quickly to here anything !   
  328.   for (int i=0;i<50000; i++) {printf(".");};   
  329.  }   
  330.     
  331.  // Attempts to aquire an empty audio source and assign it back to the caller   
  332.  // via AudioSourceID. This will lock the source   
  333.  /*****************************************************************************/  
  334.  OPAL_SOUND_MGR bool SoundManager::loadAudio( std::string filename, unsigned int *audioId,   
  335.    bool loop )   
  336.  {   
  337.   if ( filename.empty() || filename.length() > MAX_FILENAME_LENGTH )   
  338.        return false;   
  339.     
  340.   if ( mAudioSourcesInUseCount == MAX_AUDIO_SOURCES )   
  341.        return false;   // out of Audio Source slots!   
  342.     
  343.   int bufferID = -1;   // Identity of the Sound Buffer to use   
  344.   int sourceID = -1;   // Identity of the Source Buffer to use   
  345.     
  346.   alGetError();    // Clear Error Code   
  347.     
  348.   // Check and see if the pSoundFile is already loaded into a buffer   
  349.   bufferID = locateAudioBuffer( filename );   
  350.   if ( bufferID < 0 )   
  351.   {   
  352.      // The sound file isn't loaded in a buffer, lets attempt to load it on the fly   
  353.      bufferID = loadAudioInToSystem( filename );   
  354.      if ( bufferID < 0 ) return false;   // failed!   
  355.   }   
  356.     
  357.   // If you are here, the sound the requester wants to reference is in a buffer.   
  358.   // Now, we need to find a free Audio Source slot in the sound system   
  359.   sourceID = 0;   
  360.     
  361.   while ( mAudioSourceInUse[ sourceID ] == true ) sourceID++;   
  362.     
  363.   // When you are here, 'mSourceID' now represents a free Audio Source slot   
  364.   // The free slot may not be at the end of the array but in the middle of it.   
  365.   *audioId = sourceID;  // return the Audio Source ID to the caller   
  366.   mAudioSourceInUse[ sourceID ] = true// mark this Source slot as in use   
  367.   mAudioSourcesInUseCount++;    // bump the 'in use' counter   
  368.     
  369.   // Now inform OpenAL of the sound assignment and attach the audio buffer   
  370.   // to the audio source   
  371.   alSourcei( mAudioSources[sourceID], AL_BUFFER, mAudioBuffers[bufferID] );   
  372.     
  373.   // Steven : Not in the original code !!!!!   
  374.   alSourcei( mAudioSources[sourceID], AL_LOOPING, loop );   
  375.     
  376.   if ( checkALError( "loadSource()::alSourcei" ) )   
  377.        return false;   
  378.     
  379.   return true;   
  380.  }   
  381.     
  382.  // Function to check and see if the pSoundFile is already loaded into a buffer   
  383.  /*****************************************************************************/  
  384.  OPAL_SOUND_MGR int SoundManager::locateAudioBuffer( std::string filename )   
  385.  {   
  386.   for ( unsigned int b = 0; b < MAX_AUDIO_BUFFERS; b++ )   
  387.   {   
  388.      if (filename == mAudioBufferFileName[b] ) return (int) b;    
  389.      //Surely a way to optimize it with the MAP   
  390.   }   
  391.   return -1;      // not found   
  392.  }   
  393.     
  394.  // Function to load a sound file into an AudioBuffer   
  395.  /*****************************************************************************/  
  396.  OPAL_SOUND_MGR int SoundManager::loadAudioInToSystem( std::string filename )   
  397.  {   
  398.   if ( filename.empty() )   
  399.        return -1;   
  400.     
  401.   // Make sure we have audio buffers available   
  402.   if ( mAudioBuffersInUseCount == MAX_AUDIO_BUFFERS ) return -1;   
  403.     
  404.   // Find a free Audio Buffer slot   
  405.   int bufferID = 0;      // Identity of the Sound Buffer to use   
  406.     
  407.   while ( mAudioBufferInUse[ bufferID ] == true ) bufferID++;   
  408.     
  409.   // load .wav, .ogg or .au   
  410.    if ( filename.find( ".wav", 0 ) != std::string::npos )   
  411.    {   
  412.       printf(" ---> found Wav/n");   
  413.      // When you are here, bufferID now represents a free Audio Buffer slot   
  414.        // Attempt to load the SoundFile into the buffer   
  415.       if ( !loadWAV( filename, mAudioBuffers[ bufferID ] ) ) return -1;   
  416.   }   
  417.   else if ( filename.find( ".ogg", 0 ) != std::string::npos )   
  418.   {   
  419.       printf(" ---> found ogg/n");   
  420.       std::cout<<filename<<std::endl;   
  421.       if ( !loadOGG( filename, mAudioBuffers[bufferID ]) ) return -1;   
  422.     
  423.   }   
  424.   else if ( filename.find( ".au", 0 ) != std::string::npos )   
  425.   {   
  426.      printf(" ---> found au/n");   
  427.      // TODO if ( !loadAU( filename, mAudioBuffers[mBufferID]) ) return -1;   
  428.   }   
  429.     
  430.   // Successful load of the file into the Audio Buffer.   
  431.   mAudioBufferInUse[ bufferID ] = true;      // Buffer now in use   
  432.   mAudioBufferFileName[bufferID]=filename;   // save the file descriptor   
  433.     
  434.     
  435.   mAudioBuffersInUseCount++;               // bump the 'in use' counter   
  436.     
  437.   return bufferID;   
  438.  }   
  439.     
  440.  // Function to load a wave file and assigned it to a buffer   
  441.  /****************************************************************************/  
  442.  OPAL_SOUND_MGR bool SoundManager::loadWAV( std::string filename, ALuint pDestAudioBuffer )   
  443.  {   
  444.   ALenum      format;         //for the buffer format   
  445.   ALsizei      size;         //the bit depth   
  446.   ALsizei      freq;         //for the frequency of the buffer   
  447.   ALboolean   loop;         //looped   
  448.   ALvoid*      data;         //data for the buffer   
  449.     
  450.   std::string mFullPath = mAudioPath;   
  451.     
  452.   alGetError();   // Clear Error Code   
  453.     
  454.   // Load in the WAV file from disk   
  455.   //mFullPath += "//";   
  456.   mFullPath += filename;   
  457.     
  458.  #ifndef MACINTOSH_AL   
  459.    alutLoadWAVFile( (ALbyte*)mFullPath.c_str(), &format, &data, &size, &freq, &loop);   
  460.  #else   
  461.    alutLoadWAVFile( (ALbyte*)mFullPath.c_str(), &format, &data, &size, &freq);   
  462.  #endif   
  463.     
  464.   if ( checkALError("loadWAV::alutLoadWAVFile: ") )   
  465.      return false;   
  466.     
  467.   // Copy the new WAV data into the buffer   
  468.   alBufferData(pDestAudioBuffer, format, data, size, freq);   
  469.   if ( checkALError("loadWAV::alBufferData: ") )   
  470.      return false;   
  471.     
  472.   // Unload the WAV file   
  473.   alutUnloadWAV(format, data, size, freq);   
  474.   if ( checkALError("loadWAV::alutUnloadWAV: ") )   
  475.      return false;   
  476.     
  477.   return true;   
  478.  }   
  479.     
  480.  /****************************************************************************/  
  481.  OPAL_SOUND_MGR bool SoundManager::playAudio( unsigned int audioID, bool forceRestart )   
  482.  {    
  483.   // Make sure the audio source ident is valid and usable   
  484.   if ( audioID >= MAX_AUDIO_SOURCES || !mAudioSourceInUse[audioID])   
  485.        return false;   
  486.     
  487.   int sourceAudioState = 0;   
  488.     
  489.   alGetError();   
  490.     
  491.   // Are we currently playing the audio source?   
  492.   alGetSourcei( mAudioSources[audioID], AL_SOURCE_STATE, &sourceAudioState );   
  493.     
  494.   if ( sourceAudioState == AL_PLAYING )   
  495.   {   
  496.      if ( forceRestart )   
  497.           stopAudio( audioID );   
  498.        else  
  499.            return false// Not forced, so we don't do anything   
  500.   }   
  501.     
  502.   alSourcePlay( mAudioSources[ audioID ] );   
  503.   if ( checkALError( "playAudio::alSourcePlay: ") )   
  504.        return false;   
  505.     
  506.    return true;   
  507.  }   
  508.     
  509.  /****************************************************************************/  
  510.  OPAL_SOUND_MGR bool SoundManager::pauseAudio( unsigned int audioID )   
  511.  {   
  512.   // Make sure the audio source ident is valid and usable   
  513.   if ( audioID >= MAX_AUDIO_SOURCES || !mAudioSourceInUse[audioID] )   
  514.        return false;   
  515.     
  516.   alGetError();   
  517.     
  518.   alSourcePause( mAudioSources[audioID] );   
  519.     
  520.   if ( checkALError( "pauseAudio::alSourceStop ") )   
  521.        return false;   
  522.     
  523.    return true;   
  524.  }   
  525.     
  526.  /****************************************************************************/  
  527.  OPAL_SOUND_MGR bool SoundManager::pauseAllAudio( void )   
  528.  {   
  529.   if ( mAudioSourcesInUseCount >= MAX_AUDIO_SOURCES )   
  530.        return false;   
  531.     
  532.   alGetError();   
  533.     
  534.   alSourcePausev( mAudioSourcesInUseCount, mAudioSources );   
  535.     
  536.   if ( checkALError( "pauseAllAudio::alSourceStop ") )   
  537.        return false;   
  538.     
  539.    return true;   
  540.  }   
  541.     
  542.  // We could use playAudio instead !   
  543.  /****************************************************************************/  
  544.  OPAL_SOUND_MGR bool SoundManager::resumeAudio( unsigned int audioID )   
  545.  {   
  546.   // Make sure the audio source ident is valid and usable   
  547.   if ( audioID >= MAX_AUDIO_SOURCES || !mAudioSourceInUse[audioID] )   
  548.        return false;   
  549.     
  550.   alGetError();   
  551.     
  552.   // If the sound was paused the sound will resume, else it will play from   
  553.   // the beginning !   
  554.   // TODO No check for forced restart. Verify if it is what you want ?   
  555.   alSourcePlay( mAudioSources[ audioID ] );   
  556.     
  557.   if ( checkALError( "resumeAudio::alSourceStop ") )   
  558.        return false;   
  559.     
  560.    return true;   
  561.  }   
  562.     
  563.  /****************************************************************************/  
  564.  OPAL_SOUND_MGR bool SoundManager::resumeAllAudio( void )   
  565.  {   
  566.   if ( mAudioSourcesInUseCount >= MAX_AUDIO_SOURCES )   
  567.        return false;   
  568.     
  569.   alGetError();   
  570.     
  571.   int sourceAudioState = 0;   
  572.     
  573.   for ( int i=0; i<mAudioSourcesInUseCount; i++ )   
  574.   {   
  575.       // Are we currently playing the audio source?   
  576.       alGetSourcei( mAudioSources[i], AL_SOURCE_STATE, &sourceAudioState );   
  577.     
  578.       if ( sourceAudioState == AL_PAUSED )   
  579.       {   
  580.           resumeAudio( i );   
  581.       }   
  582.   }   
  583.     
  584.   if ( checkALError( "resumeAllAudio::alSourceStop ") )   
  585.        return false;   
  586.     
  587.    return true;   
  588.  }   
  589.     
  590.  /****************************************************************************/  
  591.  OPAL_SOUND_MGR bool SoundManager::stopAudio( unsigned int audioID )   
  592.  {   
  593.   // Make sure the audio source ident is valid and usable   
  594.   if ( audioID >= MAX_AUDIO_SOURCES || !mAudioSourceInUse[audioID] )   
  595.        return false;   
  596.     
  597.   alGetError();   
  598.     
  599.   alSourceStop( mAudioSources[audioID] );   
  600.     
  601.   if ( checkALError( "stopAudio::alSourceStop ") )   
  602.        return false;   
  603.     
  604.    return true;   
  605.  }   
  606.     
  607.  /****************************************************************************/  
  608.  OPAL_SOUND_MGR bool SoundManager::stopAllAudio( void )   
  609.  {   
  610.   if ( mAudioSourcesInUseCount >= MAX_AUDIO_SOURCES )   
  611.        return false;   
  612.     
  613.   alGetError();   
  614.     
  615.   for ( int i=0; i<mAudioSourcesInUseCount; i++ )   
  616.   {   
  617.       stopAudio( i );   
  618.   }   
  619.     
  620.   if ( checkALError( "stopAllAudio::alSourceStop ") )   
  621.        return false;   
  622.     
  623.    return true;   
  624.  }   
  625.     
  626.  /****************************************************************************/  
  627.  OPAL_SOUND_MGR bool SoundManager::releaseAudio( unsigned int audioID )   
  628.  {   
  629.   if ( audioID >= MAX_AUDIO_SOURCES )   
  630.        return false;   
  631.   alSourceStop( mAudioSources[audioID] );   
  632.   mAudioSourceInUse[ audioID ] = false;   
  633.   mAudioSourcesInUseCount--;   
  634.    return true;   
  635.  }   
  636.     
  637.  /****************************************************************************/  
  638.  OPAL_SOUND_MGR bool SoundManager::setSound( unsigned int audioID, Vector3 position,   
  639.    Vector3 velocity, Vector3 direction, float maxDistance,   
  640.    bool playNow, bool forceRestart, float minGain )   
  641.  {   
  642.   if ( audioID >= MAX_AUDIO_SOURCES || !mAudioSourceInUse[ audioID ] )   
  643.        return false;   
  644.     
  645.   // Set the position   
  646.   ALfloat pos[] = { position.x, position.y, position.z };   
  647.     
  648.   alSourcefv( mAudioSources[ audioID ], AL_POSITION, pos );   
  649.     
  650.   if ( checkALError( "setSound::alSourcefv:AL_POSITION" ) )   
  651.       return false;   
  652.     
  653.   // Set the veclocity   
  654.   ALfloat vel[] = { velocity.x, velocity.y, velocity.z };   
  655.     
  656.   alSourcefv( mAudioSources[ audioID ], AL_VELOCITY, vel );   
  657.     
  658.   if ( checkALError( "setSound::alSourcefv:AL_VELOCITY" ) )   
  659.       return false;   
  660.     
  661.   // Set the direction   
  662.   ALfloat dir[] = { velocity.x, velocity.y, velocity.z };   
  663.     
  664.   alSourcefv( mAudioSources[ audioID ], AL_DIRECTION, dir );   
  665.     
  666.   if ( checkALError( "setSound::alSourcefv:AL_DIRECTION" ) )   
  667.       return false;   
  668.     
  669.   // Set the max audible distance   
  670.   alSourcef( mAudioSources[ audioID ], AL_MAX_DISTANCE, maxDistance );   
  671.     
  672.   // Set the MIN_GAIN ( IMPORTANT - if not set, nothing audible! )   
  673.   alSourcef( mAudioSources[ audioID ], AL_MIN_GAIN, minGain );   
  674.     
  675.   // Set the max gain   
  676.   alSourcef( mAudioSources[ audioID ], AL_MAX_GAIN, 1.0f ); // TODO as parameter ? global ?   
  677.     
  678.   // Set the rollof factor   
  679.   alSourcef( mAudioSources[ audioID ], AL_ROLLOFF_FACTOR, 1.0f ); // TODO as parameter ?   
  680.     
  681.   // Do we play the sound now ?   
  682.   if ( playNow ) return playAudio( audioID, forceRestart ); // TODO bof... not in this fct   
  683.     
  684.   return true;   
  685.  }   
  686.     
  687.  /****************************************************************************/  
  688.  OPAL_SOUND_MGR bool SoundManager::setSoundPosition( unsigned int audioID, Vector3 position )   
  689.  {   
  690.   if ( audioID >= MAX_AUDIO_SOURCES || !mAudioSourceInUse[ audioID ] )   
  691.        return false;   
  692.     
  693.   // Set the position   
  694.   ALfloat pos[] = { position.x, position.y, position.z };   
  695.     
  696.   alSourcefv( mAudioSources[ audioID ], AL_POSITION, pos );   
  697.     
  698.   if ( checkALError( "setSound::alSourcefv:AL_POSITION" ) )   
  699.       return false;   
  700.     
  701.   return true;   
  702.  }    
  703.     
  704.  /****************************************************************************/  
  705.  OPAL_SOUND_MGR bool SoundManager::setSoundPosition( unsigned int audioID, Vector3 position,   
  706.    Vector3 velocity, Vector3 direction )   
  707.  {   
  708.   if ( audioID >= MAX_AUDIO_SOURCES || !mAudioSourceInUse[ audioID ] )   
  709.        return false;   
  710.     
  711.   // Set the position   
  712.   ALfloat pos[] = { position.x, position.y, position.z };   
  713.     
  714.   alSourcefv( mAudioSources[ audioID ], AL_POSITION, pos );   
  715.     
  716.   if ( checkALError( "setSound::alSourcefv:AL_POSITION" ) )   
  717.       return false;   
  718.     
  719.   // Set the veclocity   
  720.   ALfloat vel[] = { velocity.x, velocity.y, velocity.z };   
  721.     
  722.   alSourcefv( mAudioSources[ audioID ], AL_VELOCITY, vel );   
  723.     
  724.   if ( checkALError( "setSound::alSourcefv:AL_VELOCITY" ) )   
  725.       return false;   
  726.     
  727.   // Set the direction   
  728.   ALfloat dir[] = { velocity.x, velocity.y, velocity.z };   
  729.     
  730.   alSourcefv( mAudioSources[ audioID ], AL_DIRECTION, dir );   
  731.     
  732.   if ( checkALError( "setSound::alSourcefv:AL_DIRECTION" ) )   
  733.       return false;   
  734.     
  735.   return true;   
  736.  }   
  737.     
  738.  /****************************************************************************/  
  739.  OPAL_SOUND_MGR bool SoundManager::setListenerPosition( Vector3 position, Vector3 velocity,   
  740.    Quaternion orientation )   
  741.  {   
  742.   Vector3 axis;   
  743.     
  744.   // Set the position   
  745.   ALfloat pos[] = { position.x, position.y, position.z };   
  746.     
  747.   alListenerfv( AL_POSITION, pos );   
  748.     
  749.   if ( checkALError( "setListenerPosition::alListenerfv:AL_POSITION" ) )   
  750.       return false;   
  751.     
  752.   // Set the veclocity   
  753.   ALfloat vel[] = { velocity.x, velocity.y, velocity.z };   
  754.     
  755.   alListenerfv( AL_VELOCITY, vel );   
  756.     
  757.   if ( checkALError( "setListenerPosition::alListenerfv:AL_VELOCITY" ) )   
  758.       return false;   
  759.     
  760.   // Orientation of the listener : look at then look up   
  761.   axis = Vector3::ZERO;   
  762.   axis.x = orientation.getYaw().valueRadians();   
  763.   axis.y = orientation.getPitch().valueRadians();   
  764.   axis.z = orientation.getRoll().valueRadians();   
  765.     
  766.   // Set the direction   
  767.   ALfloat dir[] = { axis.x, axis.y, axis.z };   
  768.     
  769.   alListenerfv( AL_ORIENTATION, dir );   
  770.     
  771.   if ( checkALError( "setListenerPosition::alListenerfv:AL_DIRECTION" ) )   
  772.       return false;   
  773.     
  774.   // TODO as parameters ?   
  775.   alListenerf( AL_MAX_DISTANCE, 10000.0f );   
  776.   alListenerf( AL_MIN_GAIN, 0.0f );   
  777.   alListenerf( AL_MAX_GAIN, 1.0f );   
  778.   alListenerf( AL_GAIN, 1.0f );   
  779.     
  780.   return true;   
  781.  }   
  782.     
  783.  /****************************************************************************/  
  784.  OPAL_SOUND_MGR bool SoundManager::isOggExtensionPresent( void )   
  785.  {   
  786.   if ( alIsExtensionPresent( "AL_EXT_vorbis" ) != AL_TRUE )   
  787.   {   
  788.    printf("ERROR: SoundManager::isOggExtensionPresent : Ogg Vorbis extension not   availablee!/n");   
  789.      bOggExtensionPresent = false;   
  790.      return false;   
  791.   }   
  792.   return true;   
  793.  }    
  794.     
  795.  // Function to load a wave file and assigned it to a buffer   
  796.  // This code was taken from the plugin found on this forum :   
  797.  // http://www.ogre3d.org/phpBB2/viewtopic.php?t=7234   
  798.  //   
  799.  // TODO I didn't integrate it fow now .. because I don't need it now :-)   
  800.  //   
  801.  /****************************************************************************/  
  802.     
  803.  OPAL_SOUND_MGR bool SoundManager::loadOGGFile(std::string fileName, std::vector<char> &buffer,   
  804.  ALenum &format, ALsizei &freq)   
  805.  {   
  806.     #define BUFFER_SIZE     32768       // 32 KB buffers   
  807.     int endian = 0;                         // 0 for Little-Endian, 1 for Big-Endian   
  808.     int bitStream;   
  809.     long bytes;   
  810.     char array[BUFFER_SIZE];                // Local fixed size array   
  811.     FILE *f;   
  812.     
  813.     // Open for binary reading   
  814.     f = fopen(fileName.c_str(), "rb");   
  815.     
  816.     if (f == NULL)   
  817.         {   
  818.         std::cout << "Cannot open " << fileName << " for reading..." << std::endl;   
  819.         exit(-1);   
  820.         }   
  821.     
  822.     
  823.     vorbis_info *pInfo;   
  824.     OggVorbis_File oggFile;   
  825.     
  826.     // Try opening the given file   
  827.     if (ov_open(f, &oggFile, NULL, 0) != 0)   
  828.         {   
  829.         std::cout << "Error opening " << fileName << " for decoding..." << std::endl;   
  830.         exit(-1);   
  831.         }   
  832.     
  833.     
  834.     // Get some information about the OGG file   
  835.     pInfo = ov_info(&oggFile, -1);   
  836.     
  837.     // Check the number of channels... always use 16-bit samples   
  838.     if (pInfo->channels == 1)   
  839.         format = AL_FORMAT_MONO16;   
  840.     else  
  841.         format = AL_FORMAT_STEREO16;   
  842.     
  843.     
  844.     // The frequency of the sampling rate   
  845.     freq = pInfo->rate;   
  846.     
  847.     // Keep reading until all is read   
  848.     do  
  849.         {   
  850.         // Read up to a buffer's worth of decoded sound data   
  851.          bytes = ov_read(&oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);   
  852.     
  853.         if (bytes < 0)   
  854.             {   
  855.             ov_clear(&oggFile);   
  856.             std::cout << "Error decoding " << fileName << "..." << std::endl;   
  857.             exit(-1);   
  858.             }   
  859.     
  860.     
  861.         // Append to end of buffer   
  862.         buffer.insert(buffer.end(), array, array + bytes);   
  863.         }   
  864.     while (bytes > 0);   
  865.     
  866.     // Clean up!   
  867.     ov_clear(&oggFile);   
  868.     return true;   
  869.  }   
  870.  OPAL_SOUND_MGR bool SoundManager::loadOGG( std::string filename, ALuint pDestAudioBuffer )   
  871.  {   
  872.   ALenum       format;         //for the buffer format   
  873.   ALsizei      size;         //the bit depth   
  874.   ALsizei      freq;         //for the frequency of the buffer   
  875.   ALboolean    loop;         //looped   
  876.     
  877.   std::vector<char> bufferData;                // The sound buffer data from file   
  878.     
  879.   std::string mFullPath = mAudioPath;   
  880.     
  881.   alGetError();   // Clear Error Code   
  882.     
  883.   mFullPath += filename;   
  884.     
  885.     
  886.    loadOGGFile( mFullPath, bufferData,format,freq);   
  887.     
  888.     
  889.   alBufferData(pDestAudioBuffer, format, &bufferData[0], static_cast<ALsizei>(bufferData.size())   
  890.    , freq);   
  891.     
  892.     
  893.     
  894.     
  895.   return true;   
  896.  }    
  897.   /****************************************************************************/  
  898.  OPAL_SOUND_MGR bool SoundManager::setGain( unsigned int audioID, float gain)    
  899.   {   
  900.     if ( audioID >= MAX_AUDIO_SOURCES || !mAudioSourceInUse[ audioID ] )   
  901.        return false;   
  902.     
  903.         alSourcef(mAudioSources[audioID],AL_GAIN,gain);   
  904.     return true;   
  905. }   
  906.     
  907.     
  908.     
  909.     
  910.     
  911.     
  912.  /****************************************************************************/  
  913.  OPAL_SOUND_MGR bool SoundManager::loadDefaultSounds( std::string filename )   
  914.  {   
  915.   FILE *myfile;   
  916.   unsigned linecount=0;   
  917.   char key[255], buff[512];   
  918.     
  919.   if ( (myfile = fopen( filename.c_str() ,"r") )==NULL )   
  920.   {   
  921.     sprintf(buff, "---> Can't Open File: %s/n", filename.c_str() );   
  922.     printf( "SoundManager::loadDefaultSounds : %s/n", buff );   
  923.     return false;   
  924.   }   
  925.   fseek(myfile,0L,SEEK_SET);    // Make sure we are at the begining of the file   
  926.     
  927.   while (!feof(myfile))   
  928.   {   
  929.     fgets(buff,sizeof(buff),myfile);   // Read a line from the file.   
  930.     linecount++;   
  931.     
  932.     if (strncmp(buff,"#",1) &&        // Is this a comment line?   
  933.         strncmp(buff,"",1) &&   
  934.         strncmp(buff,"/",1))   
  935.     {   
  936.       // We have some data, attempt to load it   
  937.       strcpy(key,buff);   
  938.       trimTrailingSpace(key);   
  939.     
  940.       // First, make sure it isn't already loaded   
  941.       if ( locateAudioBuffer( key ) < 0 )   
  942.       {   
  943.         // Nope, its not already loaded   
  944.         if ( loadAudioInToSystem( key ) < 0 )   
  945.         {   
  946.           sprintf(buff,"Can't load audio file: %s/n",key);   
  947.           printf( "SoundManager::loadDefaultSounds() : %s/n", buff );   
  948.         }   
  949.       }   
  950.     }   
  951.   }   
  952.     
  953.   // Were done   
  954.   fclose(myfile);   
  955.   return true;   
  956.  }   
  957.     
  958.  // Function to trim the trailing crap from a string.   
  959.  /****************************************************************************/  
  960.  OPAL_SOUND_MGR void SoundManager::trimTrailingSpace( char *s )   
  961.  {   
  962.   char *p;   
  963.   p = s;   
  964.   if (p == NULL) return;   
  965.   for (unsigned i=0;i < (strlen(s)+1);i++)   
  966.   {   
  967.     if (__iscsym(*p) == 0 && *p != '.' && *p != '-')   
  968.     {   
  969.       *p='/0';   
  970.       break;   
  971.     }   
  972.     p++;   
  973.   }   
  974.  }  

在VS里新建一个工程,控制台应用程序,空工程,按照教程的代码添加不同的文件,全部保存,然后做如下改动:

libOpenAl.h中

 

#include "codec.h"

#include "vorbisfile.h"

// Modify this as you need.
 #ifdef OGRE
   #include "OgreVector3.h"
   #include "OgreQuaternion.h"
   using namespace Ogre;
 #else
   #include "Vector3.h"
   using namespace gameengine::utilities;
 #endif


改动为:

 

#include "vorbis/codec.h"

#include "vorbis/vorbisfile.h"

// Modify this as you need.

#include "OgreVector3.h"

#include "OgreQuaternion.h"

using namespace Ogre;


项目属性的附加库依赖项(Debug)为:ALut.lib OpenAL32.lib libvorbis.lib libogg.lib libvorbisfile.lib OgreMain_d.lib

 

编译通过后,将之前的那些DLL还有OgreMain_d.dll复制到CPP文件夹下,并为测试准备一个“test.wav”文件,同样放在CPP所在目录下,运行即可听到效果。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值