Example #1
0
void Sound::PlaySound(){
    
    alSourcePlay(source);                                                       //Play the sound buffer linked to the source
    if(alGetError() != AL_NO_ERROR) endWithError(errors[9]); //Error when playing sound
    
}
Example #2
0
Sound::Sound(char*  filePath){
    
    path  = filePath;
    //Loading of the WAVE file
    fp=fopen(filePath,"rb");                                            //Open the WAVE file
    if (!fp)  endWithError(errors[0]);                        //Could not open file
    
    //Check that the WAVE file is OK
    fread(&riff_header, sizeof(RIFF_Header), 1, fp);
    
    if(riff_header.chunkID[0]!='R' || riff_header.chunkID[1]!='I' || riff_header.chunkID[2]!='F' || riff_header.chunkID[3]!='F')            //Should be "RIFF"
        endWithError (errors[1]);                                            //Not RIFF
    
    
    if (riff_header.format[0]!='W' || riff_header.format[1]!='A' || riff_header.format[2]!='V' || riff_header.format[3]!='E')           //This part should be "WAVE"
        endWithError(errors[2]);                                            //Not WAVE
    
    fread(&wave_format, sizeof(WAVE_Format), 1, fp);
    
    if (wave_format.subChunkID[0]!='f' || wave_format.subChunkID[1]!='m' || wave_format.subChunkID[2]!='t' || wave_format.subChunkID[3]!=' ')           //This part should be "fmt "
        endWithError(errors[3]);                                            //Not fmt
    
    
    fread(type,sizeof(char),4,fp);
    if (type[0]!='d' || type[1]!='a' || type[2]!='t' || type[3]!='a')           //This part should be "data"
        endWithError(errors[4]);                                        //not data
    
    fread(&dataSize,sizeof(int),1,fp);                                        //The size of the sound data is read
    
    buf= new unsigned char[dataSize];                            //Allocate memory for the sound data
    cout << fread(buf,1,dataSize,fp) << " bytes loaded\n";           //Read the sound data and display the
    //number of bytes loaded.
    //Should be the same as the Data Size if OK
    
    
    device = alcOpenDevice(NULL);                                               //Open the device
    if(!device) endWithError(errors[5]);                         //Error during device oening
    context = alcCreateContext(device, NULL);                                   //Give the device a context
    alcMakeContextCurrent(context);                                             //Make the context the current
    if(!context) endWithError(errors[6]);                       //Error during context handeling
    
    //Stores the sound data
    frequency=wave_format.sampleRate;;                                               //The Sample Rate of the WAVE file
    
    alGenBuffers(1, &buffer);                                                    //Generate one OpenAL Buffer and link to "buffer"
    alGenSources(1, &source);                                                   //Generate one OpenAL Source and link to "source"
    if(alGetError() != AL_NO_ERROR) endWithError("Error GenSource");     //Error during buffer/source generation
    
    //Figure out the format of the WAVE file
    std::cout<<wave_format.numChannels;
    if(wave_format.bitsPerSample  == 8)
    {
        if(wave_format.numChannels  == 1)
            format = AL_FORMAT_MONO8;
        else if(wave_format.numChannels  == 2)
            format = AL_FORMAT_STEREO8;
    }
    else if(wave_format.bitsPerSample == 16)
    {
        if(wave_format.numChannels  == 1)
            format = AL_FORMAT_MONO16;
        else if(wave_format.numChannels  == 2)
            format = AL_FORMAT_STEREO16;
    }
    if(!format) endWithError(errors[7]);                      //Not valid format
    
    alBufferData(buffer, format, buf, dataSize, frequency);                    //Store the sound data in the OpenAL Buffer
    if(alGetError() != AL_NO_ERROR)
        endWithError(errors[8]);                              //Error during buffer loading
    
    //Sound setting variables
    ALfloat SourcePos[] = { 0.0, 0.0, 0.0 };
    ALfloat SourceVel[] = { 0.0, 0.0, 0.0 };
    ALfloat ListenerPos[] = { 0.0, 0.0, 0.0 };
    ALfloat ListenerVel[] = { 0.0, 0.0, 0.0 };
    ALfloat ListenerOri[] = { 0.0, 0.0, -1.0,  0.0, 1.0, 0.0 };
    //First direction vector, then vector pointing up)
    //Listener
    alListenerfv(AL_POSITION,    ListenerPos);
    alListenerfv(AL_VELOCITY,    ListenerVel);
    alListenerfv(AL_ORIENTATION, ListenerOri);
    
    //Source
    alSourcei (source, AL_BUFFER,   buffer);
    alSourcef (source, AL_PITCH,    1.0f     );
    alSourcef (source, AL_GAIN,     1.0f     );
    alSourcefv(source, AL_POSITION, SourcePos);
    alSourcefv(source, AL_VELOCITY, SourceVel);
    alSourcei (source, AL_LOOPING,  AL_FALSE );
}
Example #3
0
int main(int argc, char **argv)
{
    ALuint source, buffer;
    ALdouble offsets[2];
    ALenum state;

    /* Print out usage if no file was specified */
    if(argc < 2)
    {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 1;
    }

    /* Initialize OpenAL with the default device, and check for EFX support. */
    if(InitAL() != 0)
        return 1;

    if(!alIsExtensionPresent("AL_SOFT_source_latency"))
    {
        fprintf(stderr, "Error: AL_SOFT_source_latency not supported\n");
        CloseAL();
        return 1;
    }

    /* Define a macro to help load the function pointers. */
#define LOAD_PROC(x)  ((x) = alGetProcAddress(#x))
    LOAD_PROC(alSourcedSOFT);
    LOAD_PROC(alSource3dSOFT);
    LOAD_PROC(alSourcedvSOFT);
    LOAD_PROC(alGetSourcedSOFT);
    LOAD_PROC(alGetSource3dSOFT);
    LOAD_PROC(alGetSourcedvSOFT);
    LOAD_PROC(alSourcei64SOFT);
    LOAD_PROC(alSource3i64SOFT);
    LOAD_PROC(alSourcei64vSOFT);
    LOAD_PROC(alGetSourcei64SOFT);
    LOAD_PROC(alGetSource3i64SOFT);
    LOAD_PROC(alGetSourcei64vSOFT);

    if(alIsExtensionPresent("AL_SOFT_buffer_samples"))
    {
        LOAD_PROC(alBufferSamplesSOFT);
        LOAD_PROC(alIsBufferFormatSupportedSOFT);
    }
#undef LOAD_PROC

    /* Load the sound into a buffer. */
    buffer = LoadSound(argv[1]);
    if(!buffer)
    {
        CloseAL();
        return 1;
    }

    /* Create the source to play the sound with. */
    source = 0;
    alGenSources(1, &source);
    alSourcei(source, AL_BUFFER, buffer);
    assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");

    /* Play the sound until it finishes. */
    alSourcePlay(source);
    do {
        al_nssleep(10000000);
        alGetSourcei(source, AL_SOURCE_STATE, &state);

        /* Get the source offset and latency. AL_SEC_OFFSET_LATENCY_SOFT will
         * place the offset (in seconds) in offsets[0], and the time until that
         * offset will be heard (in seconds) in offsets[1]. */
        alGetSourcedvSOFT(source, AL_SEC_OFFSET_LATENCY_SOFT, offsets);
        printf("\rOffset: %f - Latency:%3u ms  ", offsets[0], (ALuint)(offsets[1]*1000));
        fflush(stdout);
    } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
    printf("\n");

    /* All done. Delete resources, and close OpenAL. */
    alDeleteSources(1, &source);
    alDeleteBuffers(1, &buffer);

    CloseAL();

    return 0;
}
Example #4
0
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
 * returns the new buffer ID. */
static ALuint LoadSound(const char *filename)
{
    ALenum err, format, type, channels;
    ALuint rate, buffer;
    size_t datalen;
    void *data;
    FilePtr sound;

    /* Open the audio file */
    sound = openAudioFile(filename, 1000);
    if(!sound)
    {
        fprintf(stderr, "Could not open audio in %s\n", filename);
        closeAudioFile(sound);
        return 0;
    }

    /* Get the sound format, and figure out the OpenAL format */
    if(getAudioInfo(sound, &rate, &channels, &type) != 0)
    {
        fprintf(stderr, "Error getting audio info for %s\n", filename);
        closeAudioFile(sound);
        return 0;
    }

    format = GetFormat(channels, type, alIsBufferFormatSupportedSOFT);
    if(format == AL_NONE)
    {
        fprintf(stderr, "Unsupported format (%s, %s) for %s\n",
                ChannelsName(channels), TypeName(type), filename);
        closeAudioFile(sound);
        return 0;
    }

    /* Decode the whole audio stream to a buffer. */
    data = decodeAudioStream(sound, &datalen);
    if(!data)
    {
        fprintf(stderr, "Failed to read audio from %s\n", filename);
        closeAudioFile(sound);
        return 0;
    }

    /* Buffer the audio data into a new buffer object, then free the data and
     * close the file. */
    buffer = 0;
    alGenBuffers(1, &buffer);
    alBufferSamplesSOFT(buffer, rate, format, BytesToFrames(datalen, channels, type),
                        channels, type, data);
    free(data);
    closeAudioFile(sound);

    /* Check if an error occured, and clean up if so. */
    err = alGetError();
    if(err != AL_NO_ERROR)
    {
        fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
        if(alIsBuffer(buffer))
            alDeleteBuffers(1, &buffer);
        return 0;
    }

    return buffer;
}
Example #5
0
   OpenALSound::OpenALSound(const std::string &inFilename, bool inForceMusic)
   {
      IncRef();
      mBufferID = 0;
      mIsStream = false;
      mTotalTime = -1;
      
      #ifdef HX_MACOS
      char fileURL[1024];
      GetBundleFilename(inFilename.c_str(),fileURL,1024);
      #else
      #ifdef IPHONE
      std::string asset = GetResourcePath() + gAssetBase + inFilename;
      const char *fileURL = asset.c_str();
      #else
      const char *fileURL = inFilename.c_str();
      #endif
      #endif
      
      if (!fileURL) {
         
         //LOG_SOUND("OpenALSound constructor() error in url");
         mError = "Error int url: " + inFilename;

      } else {

         QuickVec<uint8> buffer;
         int _channels;
         int _bitsPerSample;
         ALenum  format;
         ALsizei freq;
         bool ok = false; 

            //Determine the file format before we try anything
         AudioFormat type = Audio::determineFormatFromFile(std::string(fileURL));
         switch(type) {
            case eAF_ogg:
               if (inForceMusic)
               {
                  mIsStream = true;
                  mStreamPath = fileURL;
               }
               else
               {
                  ok = Audio::loadOggSampleFromFile( fileURL, buffer, &_channels, &_bitsPerSample, &freq );
               }
            break;
            case eAF_wav:
               ok = Audio::loadWavSampleFromFile( fileURL, buffer, &_channels, &_bitsPerSample, &freq );
            break;
            default:
               LOG_SOUND("Error opening sound file, unsupported type.\n");
         }
         
         if (mIsStream)
            return;
         
            //Work out the format from the data
         if (_channels == 1) {
            if (_bitsPerSample == 8 ) {
               format = AL_FORMAT_MONO8;
            } else if (_bitsPerSample == 16) {
               format = (int)AL_FORMAT_MONO16;
            }
         } else if (_channels == 2) {
            if (_bitsPerSample == 8 ) {
               format = (int)AL_FORMAT_STEREO8;
            } else if (_bitsPerSample == 16) {
               format = (int)AL_FORMAT_STEREO16;
            }
         } //channels = 2
          
         
         if (!ok) {
            LOG_SOUND("Error opening sound data\n");
            mError = "Error opening sound data";
         } else if (alGetError() != AL_NO_ERROR) {
            LOG_SOUND("Error after opening sound data\n");
            mError = "Error after opening sound data";  
         } else {
               // grab a buffer ID from openAL
            alGenBuffers(1, &mBufferID);
            
               // load the awaiting data blob into the openAL buffer.
            alBufferData(mBufferID,format,&buffer[0],buffer.size(),freq); 

               // once we have all our information loaded, get some extra flags
            alGetBufferi(mBufferID, AL_SIZE, &bufferSize);
            alGetBufferi(mBufferID, AL_FREQUENCY, &frequency);
            alGetBufferi(mBufferID, AL_CHANNELS, &channels);    
            alGetBufferi(mBufferID, AL_BITS, &bitsPerSample); 
            
         } //!ok
      }
   }
Example #6
0
   OpenALSound::OpenALSound(float *inData, int len)
   {
      IncRef();
      mBufferID = 0;
      mIsStream = false;
      
      QuickVec<uint8> buffer;
      int _channels;
      int _bitsPerSample;
      ALenum  format;
      ALsizei freq;
      bool ok = false; 
      
      //Determine the file format before we try anything
      AudioFormat type = Audio::determineFormatFromBytes(inData, len);
      
      switch(type) {
         case eAF_ogg:
            ok = Audio::loadOggSampleFromBytes(inData, len, buffer, &_channels, &_bitsPerSample, &freq );
         break;
         case eAF_wav:
            ok = Audio::loadWavSampleFromBytes(inData, len, buffer, &_channels, &_bitsPerSample, &freq );
         break;
         default:
            LOG_SOUND("Error opening sound file, unsupported type.\n");
      }
      
      //Work out the format from the data
      if (_channels == 1) {
         if (_bitsPerSample == 8 ) {
            format = AL_FORMAT_MONO8;
         } else if (_bitsPerSample == 16) {
            format = (int)AL_FORMAT_MONO16;
         }
      } else if (_channels == 2) {
         if (_bitsPerSample == 8 ) {
            format = (int)AL_FORMAT_STEREO8;
         } else if (_bitsPerSample == 16) {
            format = (int)AL_FORMAT_STEREO16;
         }
      } //channels = 2
       
      
      if (!ok) {
         LOG_SOUND("Error opening sound data\n");
         mError = "Error opening sound data";
      } else if (alGetError() != AL_NO_ERROR) {
         LOG_SOUND("Error after opening sound data\n");
         mError = "Error after opening sound data";  
      } else {
            // grab a buffer ID from openAL
         alGenBuffers(1, &mBufferID);
         
            // load the awaiting data blob into the openAL buffer.
         alBufferData(mBufferID,format,&buffer[0],buffer.size(),freq); 

            // once we have all our information loaded, get some extra flags
         alGetBufferi(mBufferID, AL_SIZE, &bufferSize);
         alGetBufferi(mBufferID, AL_FREQUENCY, &frequency);
         alGetBufferi(mBufferID, AL_CHANNELS, &channels);    
         alGetBufferi(mBufferID, AL_BITS, &bitsPerSample); 
         
      }
   }
Example #7
0
static void find_playback_device()
{
	const char *user_device = os_config_read_string( "Sound", "PlaybackDevice", NULL );
	const char *default_device = (const char*) alcGetString( NULL, ALC_DEFAULT_DEVICE_SPECIFIER );

	// in case they are the same, we only want to test it once
	if ( (user_device && default_device) && !strcmp(user_device, default_device) ) {
		user_device = NULL;
	}

    if ( alcIsExtensionPresent(NULL, (const ALCchar*)"ALC_ENUMERATION_EXT") == AL_TRUE ) {
		const char *all_devices = NULL;

        if ( alcIsExtensionPresent(NULL, (const ALCchar*)"ALC_ENUMERATE_ALL_EXT") == AL_TRUE ) {
			all_devices = (const char*) alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
		} else {
			all_devices = (const char*) alcGetString(NULL, ALC_DEVICE_SPECIFIER);
		}

		const char *str_list = all_devices;
		int ext_length = 0;

		if ( (str_list != NULL) && ((ext_length = strlen(str_list)) > 0) ) {
			while (ext_length) {
				OALdevice new_device(str_list);

				if (user_device && !strcmp(str_list, user_device)) {
					new_device.type = OAL_DEVICE_USER;
				} else if (default_device && !strcmp(str_list, default_device)) {
					new_device.type = OAL_DEVICE_DEFAULT;
				}

				PlaybackDevices.push_back( new_device );

				str_list += (ext_length + 1);
				ext_length = strlen(str_list);
			}
		}
	} else {
		if (default_device) {
			OALdevice new_device(default_device);
			new_device.type = OAL_DEVICE_DEFAULT;

			PlaybackDevices.push_back( new_device );
		}

		if (user_device) {
			OALdevice new_device(user_device);
			new_device.type = OAL_DEVICE_USER;

			PlaybackDevices.push_back( new_device );
		}
	}

	if ( PlaybackDevices.empty() ) {
		return;
	}

	std::sort( PlaybackDevices.begin(), PlaybackDevices.end(), openal_device_sort_func );


	ALCdevice *device = NULL;
	ALCcontext *context = NULL;

	// for each device that we have available, try and figure out which to use
	for (size_t idx = 0; idx < PlaybackDevices.size(); idx++) {
		OALdevice *pdev = &PlaybackDevices[idx];

		// open our specfic device
		device = alcOpenDevice( (const ALCchar*) pdev->device_name.c_str() );

		if (device == NULL) {
			continue;
		}

		context = alcCreateContext(device, NULL);

		if (context == NULL) {
			alcCloseDevice(device);
			continue;
		}

		alcMakeContextCurrent(context);
		alcGetError(device);

		// check how many sources we can create
		static const int MIN_SOURCES = 48;	// MAX_CHANNELS + 16 spare
		int si = 0;

		for (si = 0; si < MIN_SOURCES; si++) {
			ALuint source_id = 0;
			alGenSources(1, &source_id);

			if (alGetError() != AL_NO_ERROR) {
				break;
			}

			alDeleteSources(1, &source_id);
		}

		if (si == MIN_SOURCES) {
			// ok, it supports our minimum requirements
			pdev->usable = true;

			// need this for the future
			Playback_device = pdev->device_name;

			// done
			break;
		} else {
			// clean up for next pass
			alcMakeContextCurrent(NULL);
			alcDestroyContext(context);
			alcCloseDevice(device);

			context = NULL;
			device = NULL;
		}
	}

	alcMakeContextCurrent(NULL);

	if (context) {
		alcDestroyContext(context);
	}

	if (device) {
		alcCloseDevice(device);
	}
}
//------------------------------------------------------------
bool ofOpenALSoundPlayer_TimelineAdditions::loadSound(string fileName, bool is_stream){

	fileName = ofToDataPath(fileName);
	bLoadedOk = false;
	bMultiPlay = false;
	isStreaming = is_stream;

	// [1] init sound systems, if necessary
	initialize();

	// [2] try to unload any previously loaded sounds
	// & prevent user-created memory leaks
	// if they call "loadSound" repeatedly, for example

	unloadSound();
	ALenum format=AL_FORMAT_MONO16;

	if(!isStreaming){
		readFile(fileName, buffer);
	}else{
		stream(fileName, buffer);
	}

	int numFrames = buffer.size()/channels;


	if(isStreaming){
		buffers.resize(channels*2);
	}else{
		buffers.resize(channels);
	}
	alGenBuffers(buffers.size(), &buffers[0]);
	if(channels==1){
		sources.resize(1);
		alGenSources(1, &sources[0]);
		if (alGetError() != AL_NO_ERROR){
			ofLog(OF_LOG_WARNING,"ofOpenALSoundPlayer_TimelineAdditions: openAL error reported generating sources for " + fileName);
			//return false;
		}

		for(int i=0; i<(int)buffers.size(); i++){
			alBufferData(buffers[i],format,&buffer[0],buffer.size()*2,samplerate);
			if (alGetError() != AL_NO_ERROR){
				ofLog(OF_LOG_ERROR,"ofOpenALSoundPlayer_TimelineAdditions: error creating buffer");
				return false;
			}
			if(isStreaming){
				stream(fileName,buffer);
			}
		}
		if(isStreaming){
			alSourceQueueBuffers(sources[0],buffers.size(),&buffers[0]);
		}else{
			alSourcei (sources[0], AL_BUFFER,   buffers[0]);
		}

		alSourcef (sources[0], AL_PITCH,    1.0f);
		alSourcef (sources[0], AL_GAIN,     1.0f);
	    alSourcef (sources[0], AL_ROLLOFF_FACTOR,  0.0);
	    alSourcei (sources[0], AL_SOURCE_RELATIVE, AL_TRUE);
	}else{
		vector<vector<short> > multibuffer;
		multibuffer.resize(channels);
		sources.resize(channels);
		alGenSources(channels, &sources[0]);
		if(isStreaming){
			for(int s=0; s<2;s++){
				for(int i=0;i<channels;i++){
					multibuffer[i].resize(buffer.size()/channels);
					for(int j=0;j<numFrames;j++){
						multibuffer[i][j] = buffer[j*channels+i];
					}
					alBufferData(buffers[s*2+i],format,&multibuffer[i][0],buffer.size()/channels*2,samplerate);
					if (alGetError() != AL_NO_ERROR){
						ofLog(OF_LOG_ERROR,"ofOpenALSoundPlayer_TimelineAdditions: error creating stereo buffers for " + fileName);
						return false;
					}
					alSourceQueueBuffers(sources[i],1,&buffers[s*2+i]);
					stream(fileName,buffer);
				}
			}
		}else{
			for(int i=0;i<channels;i++){
				multibuffer[i].resize(buffer.size()/channels);
				for(int j=0;j<numFrames;j++){
					multibuffer[i][j] = buffer[j*channels+i];
				}
				alBufferData(buffers[i],format,&multibuffer[i][0],buffer.size()/channels*2,samplerate);
				if (alGetError() != AL_NO_ERROR){
					ofLog(OF_LOG_ERROR,"ofOpenALSoundPlayer_TimelineAdditions: error creating stereo buffers for " + fileName);
					return false;
				}
				alSourcei (sources[i], AL_BUFFER,   buffers[i]   );
			}
		}

		for(int i=0;i<channels;i++){
			if (alGetError() != AL_NO_ERROR){
				ofLog(OF_LOG_ERROR,"ofOpenALSoundPlayer_TimelineAdditions: error creating stereo sources for " + fileName);
				return false;
			}

			// only stereo panning
			if(i==0){
				float pos[3] = {-1,0,0};
				alSourcefv(sources[i],AL_POSITION,pos);
			}else{
				float pos[3] = {1,0,0};
				alSourcefv(sources[i],AL_POSITION,pos);
			}
			alSourcef (sources[i], AL_ROLLOFF_FACTOR,  0.0);
			alSourcei (sources[i], AL_SOURCE_RELATIVE, AL_TRUE);
		}
	}
	ofLogVerbose("ofOpenALSoundPlayer_TimelineAdditions: successfully loaded " + fileName);
	bLoadedOk = true;
	return true;
}
Example #9
0
/*
 * ALboolean LoadALData()
 *
 *	This function will load our sample data from the disk using the alut
 *	utility and send the data into OpenAL as a buffer. A source is then
 *	also created to play that buffer.
 */
int LoadSoundBuffers()
{
    int theerror=0;
	// Variables to load into.
    if (total_loaded_buffers==0) { fprintf(stderr,"No Sounds to load!\n");
                                   return 0; }

	ALenum format;
	ALsizei size;
	ALvoid* data;
	ALsizei freq;
	ALboolean loop;

	// Load wav data into buffers.
	alGenBuffers(total_loaded_buffers, Buffers);
	if(alGetError() != AL_NO_ERROR) { fprintf(stderr,"Error Generating Buffers!\n");
                                      return 0; }

    for (unsigned int i=0; i<total_loaded_buffers; i++)
      {
         alutLoadWAVFile((ALbyte *)filenames[i], &format, &data, &size, &freq, &loop);
         theerror=alGetError();
	     if(theerror != AL_NO_ERROR) { fprintf(stderr,"Error (%u) loading Wav sound Buffer %u %s\n",theerror,i,filenames[i]);   }

         alBufferData(Buffers[i], format, data, size, freq);
	     theerror=alGetError();
	     if(theerror != AL_NO_ERROR) { fprintf(stderr,"Error (%u) loading Wav sound Buffer %u %s\n",theerror,i,filenames[i]);   }

         alutUnloadWAV(format, data, size, freq);
	     theerror=alGetError();
	     if(theerror != AL_NO_ERROR) { fprintf(stderr,"Error (%u) loading Wav sound Buffer %u %s\n",theerror,i,filenames[i]);   }

	     free(filenames[i]); /* Release memory for filename */
      }
	// Bind buffers into audio sources.


	alGenSources(NUM_SOURCES, Sources);
    theerror=alGetError();
	if(theerror != AL_NO_ERROR) { fprintf(stderr,"Error Generating Sources (%u)!\n",theerror);
                                  return 0; }


    for (unsigned int i=0; i<total_loaded_buffers; i++)
      {
         /*alGenSources( 1, &Sources[i] );
         theerror=alGetError();
         if(theerror != AL_NO_ERROR) { cout<<"Error Generating Sources ("<<theerror<<")!\n";
                                       return false; }   */
         alSourcei (Sources[i], AL_BUFFER,   Buffers[i]   );
         alSourcef (Sources[i], AL_PITCH,    1.0f              );
         alSourcef (Sources[i], AL_GAIN,     1.0f              );
	     alSourcefv(Sources[i], AL_POSITION, SourcesPos[i]);
	     alSourcefv(Sources[i], AL_VELOCITY, SourcesVel[i]);
	     alSourcei (Sources[i], AL_LOOPING,  AL_FALSE           );
      }
	// Bind buffers into audio sources.


	// Do another error check and return.
	if(alGetError() != AL_NO_ERROR) return 0;

	SetListenerValues();

    return 1;
}
Example #10
0
/**
 * \brief Loads the file and starts playing this music.
 *
 * No other music should be playing.
 *
 * \return true if the music was loaded successfully
 */
bool Music::start() {

  if (!is_initialized()) {
    return false;
  }

  // First time: find the file.
  if (file_name.empty()) {
    find_music_file(id, file_name, format);

    if (file_name.empty()) {
      Debug::error(std::string("Cannot find music file 'musics/")
          + id + "' (tried with extensions .ogg, .it and .spc)"
      );
      return false;
    }
  }

  bool success = true;

  // create the buffers and the source
  alGenBuffers(nb_buffers, buffers);
  alGenSources(1, &source);
  alSourcef(source, AL_GAIN, volume);

  // load the music into memory
  std::string sound_buffer;
  switch (format) {

    case SPC:

      sound_buffer = QuestFiles::data_file_read(file_name);

      // Give the SPC data into the SPC decoder.
      spc_decoder->load((int16_t*) sound_buffer.data(), sound_buffer.size());

      for (int i = 0; i < nb_buffers; i++) {
        decode_spc(buffers[i], 16384);
      }
      break;

    case IT:

      sound_buffer = QuestFiles::data_file_read(file_name);

      // Give the IT data to the IT decoder
      it_decoder->load(sound_buffer);

      for (int i = 0; i < nb_buffers; i++) {
        decode_it(buffers[i], 16384);
      }
      break;

    case OGG:

      sound_buffer = QuestFiles::data_file_read(file_name);

      // Give the OGG data to the OGG decoder.
      success = ogg_decoder->load(std::move(sound_buffer), this->loop);
      if (success) {
        for (int i = 0; i < nb_buffers; i++) {
          decode_ogg(buffers[i], 16384);
        }
      }
      break;

    case NO_FORMAT:
      Debug::die("Invalid music format");
      break;
  }

  if (!success) {
    Debug::error("Cannot load music file '" + file_name + "'");
  }

  // start the streaming
  alSourceQueueBuffers(source, nb_buffers, buffers);
  int error = alGetError();
  if (error != AL_NO_ERROR) {
    std::ostringstream oss;
    oss << "Cannot initialize buffers for music '"
        << file_name << "': error " << error;
    Debug::error(oss.str());
    success = false;
  }

  alSourcePlay(source);

  // The update() function will then take care of filling the buffers

  return success;
}
Example #11
0
//based on http://ffainelli.github.io/openal-example/
Sound::Sound(std::string path)
{
    int LOAD_OK = 1;
    ALenum  format;
    ALsizei size;
    ALvoid* data;
    ALfloat freq;

    if(alGetError() != AL_NO_ERROR)
        LOAD_OK = 0;

    audioBuffer = 0;
    audioSource = 0;

    if(LOAD_OK == 1)
    {
        alGenBuffers(1,&audioBuffer);
        if (alGetError() != AL_NO_ERROR)
            LOAD_OK = 0;
    }

    if(LOAD_OK == 1)
    {
        alGenSources(1,&audioSource);
        if(alGetError() != AL_NO_ERROR)
            LOAD_OK = 0;
    }

    if(LOAD_OK == 1)
    {
        data = alutLoadMemoryFromFile(path.c_str(),&format,&size,&freq);
        LOAD_OK =  (data!=NULL) ? 1:0;
    }

    if(LOAD_OK == 1)
    {
        alBufferData(audioBuffer, format, data, size, (ALsizei)freq);
        if(alGetError() != AL_NO_ERROR)
            LOAD_OK = 0;
    }

    if(LOAD_OK == 1)
    {
        // Unload the WAV file. It's not needed now.
        alutUnloadWAV(format, data, size,(ALsizei)freq);
        if(alGetError() != AL_NO_ERROR)
            LOAD_OK = 0;
    }

    if(LOAD_OK == 1)
    {
        alSourcei(audioSource,AL_BUFFER,audioBuffer);
        if (alGetError()!=AL_NO_ERROR)
            LOAD_OK = 0;
    }

    if(LOAD_OK == 1)
    {
        // Position of the source of the sound.
        ALfloat sourcePosition[] = { 0.0f, 0.0f, 0.0f };

        // Velocity of the source of the sound.
        ALfloat sourceVelocity[] = { 0.0f, 0.0f, 0.0f };

        alSourcef(audioSource, AL_PITCH, 1.0f);
        alSourcef(audioSource, AL_GAIN, 1.0f);
        alSourcefv(audioSource, AL_POSITION, sourcePosition);
        alSourcefv(audioSource, AL_VELOCITY, sourceVelocity);

        if(alGetError() != AL_NO_ERROR)
            LOAD_OK = 0;
    }

    if(!LOAD_OK)
    {
        printf("Failed to load sound: %s\n", path.c_str());
        loaded = false;
    } else {
        loaded = true;
    }
}