Ejemplo n.º 1
0
void AudioEngine::DEBUG_PrintInfo()
{
    const ALCchar *c;

    PRINT_WARNING << "*** Audio Information ***" << std::endl;

    PRINT_WARNING << "Maximum number of sources:   " << _max_sources << std::endl;
    PRINT_WARNING << "Maximum audio cache size:    " << _max_cache_size << std::endl;
    PRINT_WARNING << "Default audio device:        " << alcGetString(_device, ALC_DEFAULT_DEVICE_SPECIFIER) << std::endl;
    PRINT_WARNING << "OpenAL Version:              " << alGetString(AL_VERSION) << std::endl;
    PRINT_WARNING << "OpenAL Renderer:             " << alGetString(AL_RENDERER) << std::endl;
    PRINT_WARNING << "OpenAL Vendor:               " << alGetString(AL_VENDOR) << std::endl;

    CheckALError();

    PRINT_WARNING << "Available OpenAL Extensions:" << std::endl;
    c = alGetString(AL_EXTENSIONS);
    bool new_extension = true;
    while(c[0]) {
        if(new_extension) {
            PRINT_WARNING << " - ";
            new_extension = false;
            continue;
        } else if(c[0] == ' ') {
            PRINT_WARNING << std::endl;
            new_extension = true;
            c++;
            continue;
        }

        PRINT_WARNING << c[0];
        c++;
    }
}
void refillALBuffers (MyStreamPlayer* player) {
	ALint processed;
	alGetSourcei (player->sources[0], AL_BUFFERS_PROCESSED, &processed);
	CheckALError ("couldn't get al_buffers_processed");
	
	while (processed > 0) {
		ALuint freeBuffer;
		alSourceUnqueueBuffers(player->sources[0], 1, &freeBuffer);
		CheckALError("couldn't unqueue buffer");
		printf ("refilling buffer %d\n", freeBuffer);
		fillALBuffer(player, freeBuffer);
		alSourceQueueBuffers(player->sources[0], 1, &freeBuffer);
		CheckALError ("couldn't queue refilled buffer");
		printf ("re-queued buffer %d\n", freeBuffer);
		processed--;
	}
	
}
Ejemplo n.º 3
0
bool AudioEngine::SingletonInitialize()
{
    if(!AUDIO_ENABLE)
        return true;

    const ALCchar *best_device = 0; // Will store the name of the 'best' device for audio playback
    ALCint highest_version = 0; // The highest version number found
    CheckALError(); // Clears errors
    CheckALCError(); // Clears errors

    // Find the highest-version device available, if the extension for device enumeration is present
    if(alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT") == AL_TRUE) {
        const ALCchar *device_list = 0;
        device_list = alcGetString(0, ALC_DEVICE_SPECIFIER); // Get list of all devices (terminated with two '0')
        if(CheckALCError() == true) {
            IF_PRINT_WARNING(AUDIO_DEBUG) << "failed to retrieve the list of available audio devices: " << CreateALCErrorString() << std::endl;
        }


        while(*device_list != 0) {  // Check all the detected devices
            ALCint major_v = 0, minor_v = 0;

            // Open a temporary device for reading in its version number
            ALCdevice *temp_device = alcOpenDevice(device_list);
            if(CheckALCError() || temp_device == NULL) {  // If we couldn't open the device, just move on to the next
                IF_PRINT_WARNING(AUDIO_DEBUG) << "couldn't open device for version checking: " << device_list << std::endl;
                device_list += strlen(device_list) + 1;
                continue;
            }

            // Create a temporary context for the device
            ALCcontext *temp_context = alcCreateContext(temp_device, 0);
            if(CheckALCError() || temp_context == NULL) {  // If we couldn't create the context, move on to the next device
                IF_PRINT_WARNING(AUDIO_DEBUG) << "couldn't create a temporary context for device: " << device_list << std::endl;
                alcCloseDevice(temp_device);
                device_list += strlen(device_list) + 1;
                continue;
            }

            // Retrieve the version number for the device
            alcMakeContextCurrent(temp_context);

            alcGetIntegerv(temp_device, ALC_MAJOR_VERSION, sizeof(ALCint), &major_v);
            alcGetIntegerv(temp_device, ALC_MINOR_VERSION, sizeof(ALCint), &minor_v);
            alcMakeContextCurrent(0); // Disable the temporary context
            alcDestroyContext(temp_context); // Destroy the temporary context
            alcCloseDevice(temp_device); // Close the temporary device

            // Check if a higher version device was found
            if(highest_version < (major_v * 10 + minor_v)) {
                highest_version = (major_v * 10 + minor_v);
                best_device = device_list;
            }
            device_list += strlen(device_list) + 1; // Go to the next device name in the list
        } // while (*device_name != 0)
    } // if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT") == AL_TRUE)

    // Open the 'best' device we found above. If no devices were previously found,
    // it will try opening the default device (= 0)
    _device = alcOpenDevice(best_device);
    if(CheckALCError() || _device == NULL) {
        PRINT_ERROR << "failed to open an OpenAL audio device: " << CreateALCErrorString() << std::endl;
        return false;
    }

    // Create an OpenAL context
    _context = alcCreateContext(_device, NULL);
    if(CheckALCError() || _context == NULL) {
        PRINT_ERROR << "failed to create an OpenAL context: " << CreateALCErrorString() << std::endl;
        alcCloseDevice(_device);
        return false;
    }

    alcMakeContextCurrent(_context);
    CheckALError(); // Clear errors
    CheckALCError(); // Clear errors

    // Create as many sources as possible (we fix an upper bound of MAX_DEFAULT_AUDIO_SOURCES)
    ALuint source;
    for(uint16 i = 0; i < _max_sources; i++) {
        alGenSources(1, &source);
        if(CheckALError() == true) {
            _max_sources = i;
            _max_cache_size = i / 4;
            break;
        }
        _audio_sources.push_back(new private_audio::AudioSource(source));
    }

    if(_max_sources == 0) {
        PRINT_ERROR << "failed to create at least one OpenAL audio source" << std::endl;
        return false;
    }

    return true;
} // bool AudioEngine::SingletonInitialize()
int main (int argc, const char * argv[]) {
	MyLoopPlayer player;
	
	// convert to an OpenAL-friendly format and read into memory
	CheckError(loadLoopIntoBuffer(&player),
			   "Couldn't load loop into buffer") ;
	
	// set up OpenAL buffer
	ALCdevice* alDevice = alcOpenDevice(NULL);
	CheckALError ("Couldn't open AL device"); // default device
	ALCcontext* alContext = alcCreateContext(alDevice, 0);
	CheckALError ("Couldn't open AL context");
	alcMakeContextCurrent (alContext);
	CheckALError ("Couldn't make AL context current");
	ALuint buffers[1];
	alGenBuffers(1, buffers);
	CheckALError ("Couldn't generate buffers");
	alBufferData(*buffers,
				 AL_FORMAT_MONO16,
				 player.sampleBuffer,
				 player.bufferSizeBytes,
				 player.dataFormat.mSampleRate);
	
	// AL copies the samples, so we can free them now
	free(player.sampleBuffer);
	
	// set up OpenAL source
	alGenSources(1, player.sources);
	CheckALError ("Couldn't generate sources");
	alSourcei(player.sources[0], AL_LOOPING, AL_TRUE);
	CheckALError ("Couldn't set source looping property");
	alSourcef(player.sources[0], AL_GAIN, AL_MAX_GAIN);
	CheckALError("Couldn't set source gain");
	updateSourceLocation(player);
	CheckALError ("Couldn't set initial source position");
	
	// connect buffer to source
	alSourcei(player.sources[0], AL_BUFFER, buffers[0]);
	CheckALError ("Couldn't connect buffer to source");
	
	// set up listener
	alListener3f (AL_POSITION, 0.0, 0.0, 0.0);
	CheckALError("Couldn't set listner position");
	
	//	ALfloat listenerOrientation[6]; // 3 vectors: forward x,y,z components, then up x,y,z
	//	listenerOrientation[2] = -1.0;
	//	listenerOrientation[0] = listenerOrientation [1] = 0.0;
	//	listenerOrientation[3] = listenerOrientation [4] =  listenerOrientation[5] = 0.0;
	//	alListenerfv (AL_ORIENTATION, listenerOrientation);
	
	// start playing
	// alSourcePlayv (1, player.sources);
	alSourcePlay(player.sources[0]);
	CheckALError ("Couldn't play");
	
	// and wait
	printf("Playing...\n");
	time_t startTime = time(NULL);
	do
	{
		// get next theta
		updateSourceLocation(player);
		CheckALError ("Couldn't set looping source position");
		CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
	} while (difftime(time(NULL), startTime) < RUN_TIME);
	
	// cleanup:
	alSourceStop(player.sources[0]);
	alDeleteSources(1, player.sources);
	alDeleteBuffers(1, buffers);
	alcDestroyContext(alContext);
	alcCloseDevice(alDevice);
	printf ("Bottom of main\n");
}
int main (int argc, const char * argv[]) {
	MyStreamPlayer player;
	
	// prepare the ExtAudioFile for reading
	CheckError(setUpExtAudioFile(&player),
			   "Couldn't open ExtAudioFile") ;
	
	// set up OpenAL buffers
	ALCdevice* alDevice = alcOpenDevice(NULL);
	CheckALError ("Couldn't open AL device"); // default device
	ALCcontext* alContext = alcCreateContext(alDevice, 0);
	CheckALError ("Couldn't open AL context");
	alcMakeContextCurrent (alContext);
	CheckALError ("Couldn't make AL context current");
	ALuint buffers[BUFFER_COUNT];
	alGenBuffers(BUFFER_COUNT, buffers);
	CheckALError ("Couldn't generate buffers");
	
	for (int i=0; i<BUFFER_COUNT; i++) {
		fillALBuffer(&player, buffers[i]);
	}
	
	// set up streaming source
	alGenSources(1, player.sources);
	CheckALError ("Couldn't generate sources");
	alSourcef(player.sources[0], AL_GAIN, AL_MAX_GAIN);
	CheckALError("Couldn't set source gain");
	updateSourceLocation(player);
	CheckALError ("Couldn't set initial source position");
	
	// queue up the buffers on the source
	alSourceQueueBuffers(player.sources[0],
						 BUFFER_COUNT,
						 buffers);
	CheckALError("Couldn't queue buffers on source");
	
	// set up listener
	alListener3f (AL_POSITION, 0.0, 0.0, 0.0);
	CheckALError("Couldn't set listner position");
	
	// start playing
	alSourcePlayv (1, player.sources);
	CheckALError ("Couldn't play");
	
	// and wait
	printf("Playing...\n");
	time_t startTime = time(NULL);
	do
	{
		// get next theta
		updateSourceLocation(player);
		CheckALError ("Couldn't set source position");
		
		// refill buffers if needed
		refillALBuffers (&player);
		
		CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
	} while (difftime(time(NULL), startTime) < RUN_TIME);
	
	// cleanup:
	alSourceStop(player.sources[0]);
	alDeleteSources(1, player.sources);
	alDeleteBuffers(BUFFER_COUNT, buffers);
	alcDestroyContext(alContext);
	alcCloseDevice(alDevice);
	printf ("Bottom of main\n");
}
Ejemplo n.º 6
0
void OpenALStream::SoundLoop()
{
  Common::SetCurrentThreadName("Audio thread - openal");

  bool surround_capable = SConfig::GetInstance().bDPL2Decoder;
  bool float32_capable = false;
  bool fixed32_capable = false;

#if defined(__APPLE__)
  surround_capable = false;
#endif

  u32 ulFrequency = m_mixer->GetSampleRate();
  numBuffers = SConfig::GetInstance().iLatency + 2;  // OpenAL requires a minimum of two buffers

  memset(uiBuffers, 0, numBuffers * sizeof(ALuint));
  uiSource = 0;

  if (alIsExtensionPresent("AL_EXT_float32"))
    float32_capable = true;

  // As there is no extension to check for 32-bit fixed point support
  // and we know that only a X-Fi with hardware OpenAL supports it,
  // we just check if one is being used.
  if (strstr(alGetString(AL_RENDERER), "X-Fi"))
    fixed32_capable = true;

  // Clear error state before querying or else we get false positives.
  ALenum err = alGetError();

  // Generate some AL Buffers for streaming
  alGenBuffers(numBuffers, (ALuint*)uiBuffers);
  err = CheckALError("generating buffers");

  // Generate a Source to playback the Buffers
  alGenSources(1, &uiSource);
  err = CheckALError("generating sources");

  // Set the default sound volume as saved in the config file.
  alSourcef(uiSource, AL_GAIN, fVolume);

  // TODO: Error handling
  // ALenum err = alGetError();

  unsigned int nextBuffer = 0;
  unsigned int numBuffersQueued = 0;
  ALint iState = 0;

  soundTouch.setChannels(2);
  soundTouch.setSampleRate(ulFrequency);
  soundTouch.setTempo(1.0);
  soundTouch.setSetting(SETTING_USE_QUICKSEEK, 0);
  soundTouch.setSetting(SETTING_USE_AA_FILTER, 0);
  soundTouch.setSetting(SETTING_SEQUENCE_MS, 1);
  soundTouch.setSetting(SETTING_SEEKWINDOW_MS, 28);
  soundTouch.setSetting(SETTING_OVERLAP_MS, 12);

  while (m_run_thread.IsSet())
  {
    // Block until we have a free buffer
    int numBuffersProcessed;
    alGetSourcei(uiSource, AL_BUFFERS_PROCESSED, &numBuffersProcessed);
    if (numBuffers == numBuffersQueued && !numBuffersProcessed)
    {
      soundSyncEvent.Wait();
      continue;
    }

    // Remove the Buffer from the Queue.
    if (numBuffersProcessed)
    {
      ALuint unqueuedBufferIds[OAL_MAX_BUFFERS];
      alSourceUnqueueBuffers(uiSource, numBuffersProcessed, unqueuedBufferIds);
      err = CheckALError("unqueuing buffers");

      numBuffersQueued -= numBuffersProcessed;
    }

    // num_samples_to_render in this update - depends on SystemTimers::AUDIO_DMA_PERIOD.
    const u32 stereo_16_bit_size = 4;
    const u32 dma_length = 32;
    const u64 ais_samples_per_second = 48000 * stereo_16_bit_size;
    u64 audio_dma_period = SystemTimers::GetTicksPerSecond() /
                           (AudioInterface::GetAIDSampleRate() * stereo_16_bit_size / dma_length);
    u64 num_samples_to_render =
        (audio_dma_period * ais_samples_per_second) / SystemTimers::GetTicksPerSecond();

    unsigned int numSamples = (unsigned int)num_samples_to_render;
    unsigned int minSamples =
        surround_capable ? 240 : 0;  // DPL2 accepts 240 samples minimum (FWRDURATION)

    numSamples = (numSamples > OAL_MAX_SAMPLES) ? OAL_MAX_SAMPLES : numSamples;
    numSamples = m_mixer->Mix(realtimeBuffer, numSamples, false);

    // Convert the samples from short to float
    float dest[OAL_MAX_SAMPLES * STEREO_CHANNELS];
    for (u32 i = 0; i < numSamples * STEREO_CHANNELS; ++i)
      dest[i] = (float)realtimeBuffer[i] / (1 << 15);

    soundTouch.putSamples(dest, numSamples);

    double rate = (double)m_mixer->GetCurrentSpeed();
    if (rate <= 0)
    {
      Core::RequestRefreshInfo();
      rate = (double)m_mixer->GetCurrentSpeed();
    }

    // Place a lower limit of 10% speed.  When a game boots up, there will be
    // many silence samples.  These do not need to be timestretched.
    if (rate > 0.10)
    {
      soundTouch.setTempo(rate);
      if (rate > 10)
      {
        soundTouch.clear();
      }
    }

    unsigned int nSamples = soundTouch.receiveSamples(sampleBuffer, OAL_MAX_SAMPLES * numBuffers);

    if (nSamples <= minSamples)
      continue;

    if (surround_capable)
    {
      float dpl2[OAL_MAX_SAMPLES * OAL_MAX_BUFFERS * SURROUND_CHANNELS];
      DPL2Decode(sampleBuffer, nSamples, dpl2);

      // zero-out the subwoofer channel - DPL2Decode generates a pretty
      // good 5.0 but not a good 5.1 output.  Sadly there is not a 5.0
      // AL_FORMAT_50CHN32 to make this super-explicit.
      // DPL2Decode output: LEFTFRONT, RIGHTFRONT, CENTREFRONT, (sub), LEFTREAR, RIGHTREAR
      for (u32 i = 0; i < nSamples; ++i)
      {
        dpl2[i * SURROUND_CHANNELS + 3 /*sub/lfe*/] = 0.0f;
      }

      if (float32_capable)
      {
        alBufferData(uiBuffers[nextBuffer], AL_FORMAT_51CHN32, dpl2,
                     nSamples * FRAME_SURROUND_FLOAT, ulFrequency);
      }
      else if (fixed32_capable)
      {
        int surround_int32[OAL_MAX_SAMPLES * SURROUND_CHANNELS * OAL_MAX_BUFFERS];

        for (u32 i = 0; i < nSamples * SURROUND_CHANNELS; ++i)
        {
          // For some reason the ffdshow's DPL2 decoder outputs samples bigger than 1.
          // Most are close to 2.5 and some go up to 8. Hard clamping here, we need to
          // fix the decoder or implement a limiter.
          dpl2[i] = dpl2[i] * (INT64_C(1) << 31);
          if (dpl2[i] > INT_MAX)
            surround_int32[i] = INT_MAX;
          else if (dpl2[i] < INT_MIN)
            surround_int32[i] = INT_MIN;
          else
            surround_int32[i] = (int)dpl2[i];
        }

        alBufferData(uiBuffers[nextBuffer], AL_FORMAT_51CHN32, surround_int32,
                     nSamples * FRAME_SURROUND_INT32, ulFrequency);
      }
      else
      {
        short surround_short[OAL_MAX_SAMPLES * SURROUND_CHANNELS * OAL_MAX_BUFFERS];

        for (u32 i = 0; i < nSamples * SURROUND_CHANNELS; ++i)
        {
          dpl2[i] = dpl2[i] * (1 << 15);
          if (dpl2[i] > SHRT_MAX)
            surround_short[i] = SHRT_MAX;
          else if (dpl2[i] < SHRT_MIN)
            surround_short[i] = SHRT_MIN;
          else
            surround_short[i] = (int)dpl2[i];
        }

        alBufferData(uiBuffers[nextBuffer], AL_FORMAT_51CHN16, surround_short,
                     nSamples * FRAME_SURROUND_SHORT, ulFrequency);
      }

      err = CheckALError("buffering data");
      if (err == AL_INVALID_ENUM)
      {
        // 5.1 is not supported by the host, fallback to stereo
        WARN_LOG(AUDIO,
                 "Unable to set 5.1 surround mode.  Updating OpenAL Soft might fix this issue.");
        surround_capable = false;
      }
    }
    else
    {
      if (float32_capable)
      {
        alBufferData(uiBuffers[nextBuffer], AL_FORMAT_STEREO_FLOAT32, sampleBuffer,
                     nSamples * FRAME_STEREO_FLOAT, ulFrequency);

        err = CheckALError("buffering float32 data");
        if (err == AL_INVALID_ENUM)
        {
          float32_capable = false;
        }
      }
      else if (fixed32_capable)
      {
        // Clamping is not necessary here, samples are always between (-1,1)
        int stereo_int32[OAL_MAX_SAMPLES * STEREO_CHANNELS * OAL_MAX_BUFFERS];
        for (u32 i = 0; i < nSamples * STEREO_CHANNELS; ++i)
          stereo_int32[i] = (int)((float)sampleBuffer[i] * (INT64_C(1) << 31));

        alBufferData(uiBuffers[nextBuffer], AL_FORMAT_STEREO32, stereo_int32,
                     nSamples * FRAME_STEREO_INT32, ulFrequency);
      }
      else
      {
        // Convert the samples from float to short
        short stereo[OAL_MAX_SAMPLES * STEREO_CHANNELS * OAL_MAX_BUFFERS];
        for (u32 i = 0; i < nSamples * STEREO_CHANNELS; ++i)
          stereo[i] = (short)((float)sampleBuffer[i] * (1 << 15));

        alBufferData(uiBuffers[nextBuffer], AL_FORMAT_STEREO16, stereo,
                     nSamples * FRAME_STEREO_SHORT, ulFrequency);
      }
    }

    alSourceQueueBuffers(uiSource, 1, &uiBuffers[nextBuffer]);
    err = CheckALError("queuing buffers");

    numBuffersQueued++;
    nextBuffer = (nextBuffer + 1) % numBuffers;

    alGetSourcei(uiSource, AL_SOURCE_STATE, &iState);
    if (iState != AL_PLAYING)
    {
      // Buffer underrun occurred, resume playback
      alSourcePlay(uiSource);
      err = CheckALError("occurred resuming playback");
    }
  }
}
Ejemplo n.º 7
0
void osaOpenAL::OpenFile(const mtsStdString & fName)
{
    Stop();

    if (Data) {
        alDeleteBuffers(1, SoundBuffer);
        alDeleteSources(1, SoundSource);
        delete[] Data;
        Data = 0;
    }

    if (SoundFile) {
        CMN_LOG_CLASS_RUN_DEBUG << "Closing file" <<std::endl;
        fclose(SoundFile);
        SoundFile = 0;
    }

    double startTime = 0;
    double bytesPerWholeSample = 0;

    FileName = fName.Data;
    int pos = FileName.Data.find_last_of('.');
    if (pos == std::string::npos
            || pos == 0
            || (SoundFile = ::fopen(FileName.Data.c_str(), "rb")) == 0 ) {
        CMN_LOG_CLASS_RUN_ERROR << "OpenFile: file name is not valid: " << FileName.Data << std::endl;
        Time = 0;
        return;
    }

    // using CAI format
    if (FileName.Data.substr(pos + 1) == "cai") {
        CMN_LOG_CLASS_RUN_VERBOSE << "FileOpen: opening CAI file "<< FileName.Data << std::endl;
        FType = osaOpenAL::CAI;

        if (::fread(CAIHeader, 1, sizeof(osaOpenALCAIHeader), SoundFile)) {
            unsigned int tmpCurrent = ftell(SoundFile);

            fseek(SoundFile, 0, SEEK_END);
            NumDataBytes = ftell(SoundFile) - tmpCurrent;
            fseek(SoundFile, tmpCurrent, SEEK_SET);
            //this is the whole file in memory.

            double bytesPerWholeSample =  CAIHeader->nBytesPerSample * CAIHeader->nChannels;

            LengthInSec = (double)NumDataBytes / bytesPerWholeSample  / (double)CAIHeader->frequency;
            CMN_LOG_CLASS_RUN_VERBOSE << "OpenFile: file length is : "
                                      << LengthInSec.Data << " seconds" << std::endl;

            StartTimeAbsolute = CAIHeader->StartTime;
            CMN_LOG_CLASS_RUN_VERBOSE << std::setprecision(3) << std::fixed
                                      <<"OpenFile: absolute start time: " << StartTimeAbsolute.Data << std::endl;

            Data = new char[NumDataBytes];

            ::fread(Data, 1, NumDataBytes, SoundFile);

            ALenum tmpFormat;

            if (CAIHeader->nChannels == 1) {
                if (CAIHeader->nBytesPerSample == 1) {
                    tmpFormat = AL_FORMAT_MONO8;
                } else {
                    tmpFormat = AL_FORMAT_MONO16;
                }
            } else {
                if (CAIHeader->nBytesPerSample == 1) {
                    tmpFormat = AL_FORMAT_STEREO8;
                } else {
                    tmpFormat = AL_FORMAT_STEREO16;
                }
            }

            *SoundSettings = *CAIHeader;

            alGetError();
            alGenBuffers(1, SoundBuffer);
            std::string err;
            if (CheckALError(err)) {
                CMN_LOG_CLASS_RUN_ERROR << "OpenFile: OpenAL error: " << err
                                        <<" - while generating data BUFFER" << std::endl;
            }
            alBufferData(SoundBuffer[0], tmpFormat, Data, NumDataBytes, CAIHeader->frequency);
            alGenSources(1, SoundSource);

            if (CheckALError(err)) {
                CMN_LOG_CLASS_RUN_ERROR << "OpenFile: OpenAL error: " << err
                                        << "- while creating data buffer and SOURCES" << std::endl;
            }

            alSourcei(SoundSource[0], AL_BUFFER, SoundBuffer[0]);
        }

        Seek(0);
        RangeChangedEvent();
    }
    // WAV format
    else if (FileName.Data.substr(pos+1) == "wav") {
        CMN_LOG_CLASS_RUN_VERBOSE << "FileOpen: opening WAV file " << FileName.Data << std::endl;
        FType = osaOpenAL::WAV;

        //! \todo at the moment we can't read other wav files. To fix, look for tags first.
        //Test if we are using the old waveheader

        osaOpenALCISSTWAVHeader  cisstWAVHeader;

        ::fread(&cisstWAVHeader, 1, sizeof(osaOpenALCISSTWAVHeader), SoundFile);

        if (strcmp(cisstWAVHeader.szTime, "abTM") == 0) {

            CMN_LOG_CLASS_RUN_WARNING << "Using old wav file version" <<std::endl;
            unsigned int tmpCurrent = ftell(SoundFile);

            fseek(SoundFile, 0, SEEK_END);
            NumDataBytes = ftell(SoundFile) - tmpCurrent;
            fseek(SoundFile, tmpCurrent, SEEK_SET);
            //this is the whole file in memory.

            if (cisstWAVHeader.wfex.wFormatTag != 1) {
                CMN_LOG_CLASS_RUN_ERROR << "OpenFile: wrong WAV format for file: " << FileName.Data << std::endl;
            }

            SoundSettings->nBytesPerSample   = cisstWAVHeader.wfex.wBitsPerSample / 8;
            SoundSettings->nChannels         = cisstWAVHeader.wfex.nChannels;
            SoundSettings->frequency         = cisstWAVHeader.wfex.nSamplesPerSec;

            bytesPerWholeSample =  cisstWAVHeader.wfex.nBlockAlign;  // WAV_Header->wfex.nChannels * WAV_Header->wfex.wBitsPerSample / 8
            startTime =   cisstWAVHeader.timeStamp;
        }
        else {

            fseek(SoundFile, 0, SEEK_SET);
            ::fread(WAVHeader, 1, sizeof(osaOpenALWAVHeader), SoundFile);

            unsigned int tmpCurrent = ftell(SoundFile);

            fseek(SoundFile, 0, SEEK_END);
            NumDataBytes = ftell(SoundFile) - tmpCurrent;
            fseek(SoundFile, tmpCurrent, SEEK_SET);
            //this is the whole file in memory.

            if (WAVHeader->wfex.wFormatTag != 1) {
                CMN_LOG_CLASS_RUN_ERROR << "OpenFile: wrong WAV format for file: " << FileName.Data << std::endl;
            }

            SoundSettings->nBytesPerSample   = WAVHeader->wfex.wBitsPerSample / 8;
            SoundSettings->nChannels         = WAVHeader->wfex.nChannels;
            SoundSettings->frequency         = WAVHeader->wfex.nSamplesPerSec;

            bytesPerWholeSample =  WAVHeader->wfex.nBlockAlign;  // WAV_Header->wfex.nChannels * WAV_Header->wfex.wBitsPerSample / 8

        }


        LengthInSec = (double)NumDataBytes / bytesPerWholeSample  / (double) SoundSettings->frequency;

        CMN_LOG_CLASS_RUN_VERBOSE << "OpenFile: file length is: "
                                  << LengthInSec.Data << " seconds" << std::endl;

        Data = new char[NumDataBytes];

        ::fread(Data, 1, NumDataBytes, SoundFile);

        CMN_LOG_CLASS_RUN_VERBOSE << "OpenFile: audioData size is: " << NumDataBytes <<std::endl;
        // << " bytes; WAV header reports Data Size: " << WAVHeader->lDataSize
        // << " bytes" << std::endl;

        ALenum tmpFormat;

        if (SoundSettings->nChannels == 1) {
            if (SoundSettings->nBytesPerSample == 1) {
                tmpFormat = AL_FORMAT_MONO8;
            } else {
                tmpFormat = AL_FORMAT_MONO16;
            }
        }
        else {
            if (SoundSettings->nBytesPerSample == 1) {
                tmpFormat = AL_FORMAT_STEREO8;
            }
            else {
                tmpFormat = AL_FORMAT_STEREO16;
            }
        }

        //Open text file containing the datatimestamps:
        std::string headerLine;
        std::string timeStampFileName = FileName.Data + std::string(".txt");
        std::ifstream timeStampFile(timeStampFileName.c_str());
        double startTime = 0;
        int    bytePos   = 0;
        double timestamp = 0;
        TimeStamps.clear();
        SamplePosInBytes.clear();

        if (timeStampFile.is_open())
        {
            getline (timeStampFile,headerLine);
            timeStampFile>>startTime>>bytePos;
            while (!timeStampFile.eof()) {
                timeStampFile>>timestamp>>bytePos;
                TimeStamps.push_back(timestamp);
                SamplePosInBytes.push_back(bytePos);
            }
        }