Beispiel #1
0
bool initSoundStuff (HWND hwnd) {

	if(!alureInitDevice(NULL, NULL))
	{
		debugOut( "Failed to open OpenAL device: %s\n",
				alureGetErrorString());
		return 1;
	}

	int a;
	for (a = 0; a < MAX_SAMPLES; a ++) {
		soundCache[a].stream = NULL;
		soundCache[a].playing = false;
		soundCache[a].fileLoaded = -1;
		soundCache[a].looping = false;
		intpointers[a] = a;
	}

	for (a = 0; a < MAX_MODS; a ++) {
		modCache[a].stream = NULL;
		modCache[a].playing = false;
	}

	if (! alureUpdateInterval(0.01))
	{
		debugOut("Failed to set Alure update interval: %s\n",
				alureGetErrorString());
		return 1;
	}
	return soundOK = true;
}
Beispiel #2
0
void playMovieStream (int a) {
	if (! soundOK) return;
	ALboolean ok;
	ALuint src;
	
	alGenSources(1, &src);
	if(alGetError() != AL_NO_ERROR)
	{
		debugOut( "Failed to create OpenAL source!\n");
		return;
	}
	
	alSourcef (src, AL_GAIN, (float) soundCache[a].vol / 256);
	
	ok = alurePlaySourceStream(src, soundCache[a].stream,
								   10, 0, sound_eos_callback, &intpointers[a]);
	
	if(!ok) {
		debugOut("Failed to play stream: %s\n", alureGetErrorString());
		alDeleteSources(1, &src);
		if(alGetError() != AL_NO_ERROR)
		{
			debugOut("Failed to delete OpenAL source!\n");
		}
		soundCache[a].playingOnSource = 0;
	} else {
		soundCache[a].playingOnSource = src;
		soundCache[a].playing = true;
	}
}
Beispiel #3
0
void SoundPlayer::play(std::string filename) {
	if(__SoundPlayer_audio_is_disabled) {
		return;
	}

	pthread_mutex_lock(&control_mutex);
	_player_stop();
	pthread_mutex_lock(&player_mutex);

	stop = true;

	stream = alureCreateStreamFromFile(filename.c_str(), 19200, 2, buf);

	if(stream == AL_NONE) {
		printf("Error loading file %s: %s\n", filename.c_str(), alureGetErrorString());
	}else if(!ALSources::get(sourceID)) {
		printf("No OpenAL sources available\n");
		alureDestroyStream(stream, 1, buf);
	} else {
		stop = paused = false;
		alSourcef(sourceID, AL_GAIN, volume);
		alSource3f(sourceID, AL_POSITION, x, y, z);
		alurePlaySourceStream(sourceID, stream, 2, 0, stopped_callback, this);
	}

	pthread_mutex_unlock(&control_mutex);
}
void UOpenALAudioSubsystem::RegisterSound( USound* Sound )
{
	guard(UOpenALAudioSubsystem::RegisterSound);

	checkSlow(Sound);
	if( !Sound->Handle )
	{
		// Set the handle to avoid reentrance.
		Sound->Handle = (void*)-1;

		// Load the data.
		Sound->Data.Load();
		debugf( NAME_DevSound, TEXT("Register sound: %s (%i)"), Sound->GetPathName(), Sound->Data.Num() );
		check(Sound->Data.Num()>0);

		// Flush errors.
		alGetError();

		// Create the buffer.
		FAudioBuffer *Sample = new FAudioBuffer;
		Sample->Id = alureCreateBufferFromMemory( &Sound->Data(0), Sound->Data.Num() );
		if( Sample->Id == AL_NONE )
			appErrorf(
				TEXT("Couldn't create buffer for sound '%s': %s"),
				Sound->GetPathName(), alureGetErrorString()
			);
		Sound->Handle = Sample;

		// Unload the data.
		Sound->Data.Unload();
	}

	unguard;
}
std::shared_ptr<Sound> System::GetSound(const std::string& id) {
    if(sounds.find(id) != sounds.end()) {
        std::shared_ptr<Sound> sound(new Sound);
        alGenSources(1, &sound->src);

        if(alGetError() != AL_NO_ERROR) {
            std::cout << "Failed to create OpenAL source for sound: " << id << std::endl;
            return nullptr;
        }

        // create openal buffer from source
        sound->buff = alureCreateBufferFromFile(sounds[id]->src.c_str());

        if(sound->buff  == 0) {
            std::cout << "Could not load: " << sound->buff << " : " << alureGetErrorString() << std::endl;
            return nullptr;
        }

        alSourcei(sound->src, AL_BUFFER, sound->buff);
        alSourcei(sound->src, AL_LOOPING, sounds[id]->loop);
        alSourcef(sound->src, AL_GAIN, sounds[id]->volume);
        alSourcei(sound->src, AL_SOURCE_RELATIVE, !sounds[id]->spatial);

        return sound;
    }

    return nullptr;
}
Beispiel #6
0
int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate, 
				   ALuint (*callback)(void *userdata, ALubyte *data, ALuint bytes)) {
	if (! soundOK) return 0;

	int retval;
	int a = findEmptySoundSlot ();
	freeSound (a);
	
	soundCache[a].looping = false;
	// audioChannel * sampleRate gives us a buffer of half a second. Not much, but it should be enough.
	soundCache[a].stream = alureCreateStreamFromCallback(
					 callback,
					 &intpointers[a], format, samplerate,
					 audioChannels*samplerate, 0, NULL);
	
	if (soundCache[a].stream != NULL) {
		soundCache[a].fileLoaded = f;
		soundCache[a].vol = defSoundVol;
		retval = a;
	} else {
		debugOut("Failed to create stream from sound: %s\n",
				 alureGetErrorString());
		warning (ERROR_SOUND_ODDNESS);
		soundCache[a].stream = NULL;
		soundCache[a].playing = false;
		soundCache[a].playingOnSource = 0;
		soundCache[a].fileLoaded = -1;
		retval = -1;
	}
	//fprintf (stderr, "Stream %d created. Sample rate: %d Channels: %d\n", retval, samplerate, audioChannels);
	
	return retval;
}
Beispiel #7
0
void stopMOD (int i) {
	if (! soundOK) return;
	alGetError();
	if (modCache[i].playing) {
		if (! alureStopSource(modCache[i].playingOnSource, AL_TRUE)) {
			debugOut("Failed to stop source: %s\n",
						alureGetErrorString());
		}
	}
}
Beispiel #8
0
bool playMOD (int f, int a, int fromTrack) {
	if (! soundOK) return true;
	stopMOD (a);

	setResourceForFatal (f);
	uint32_t length = openFileFromNum (f);
	if (length == 0) {
		finishAccess();
		setResourceForFatal (-1);
		return false;
	}

	unsigned char * memImage;
	memImage = (unsigned char *) loadEntireFileToMemory (bigDataFile, length);
	if (! memImage) return fatal (ERROR_MUSIC_MEMORY_LOW);

	modCache[a].stream = alureCreateStreamFromMemory(memImage, length, 19200, 0, NULL);
	delete memImage;

	if (modCache[a].stream != NULL) {
		setMusicVolume (a, defVol);
		if (! alureSetStreamOrder (modCache[a].stream, fromTrack)) {
			debugOut( "Failed to set stream order: %s\n",
						alureGetErrorString());
		}

		playStream (a, true, true);

	} else {
		debugOut("Failed to create stream from MOD: %s\n",
						alureGetErrorString());
		warning (ERROR_MUSIC_ODDNESS);
		soundCache[a].stream = NULL;
		soundCache[a].playing = false;
		soundCache[a].playingOnSource = 0;
	}
	setResourceForFatal (-1);

	return true;
}
Beispiel #9
0
void killSoundStuff () {
	if (! soundOK) return;

	SilenceIKillYou = true;
	for (int i = 0; i < MAX_SAMPLES; i ++) {
		if (soundCache[i].playing) {
			if (! alureStopSource(soundCache[i].playingOnSource, AL_TRUE)) {
				debugOut( "Failed to stop source: %s\n",
							alureGetErrorString());
			}
		}

		if (soundCache[i].stream != NULL) {
			if (! alureDestroyStream(soundCache[i].stream, 0, NULL)) {
				debugOut("Failed to destroy stream: %s\n",
							alureGetErrorString());
			}
		}
	}

	for (int i = 0; i < MAX_MODS; i ++) {
		if (modCache[i].playing) {
			if (! alureStopSource(modCache[i].playingOnSource, AL_TRUE)) {
				debugOut( "Failed to stop source: %s\n",
							alureGetErrorString());
			}
		}

		if (modCache[i].stream != NULL) {
			if (! alureDestroyStream(modCache[i].stream, 0, NULL)) {
				debugOut("Failed to destroy stream: %s\n",
							alureGetErrorString());
			}
		}
	}

	SilenceIKillYou = false;

	alureShutdownDevice();
}
Beispiel #10
0
void freeSound (int a) {
	if (! soundOK) return;
	// Clear OpenAL errors to make sure they don't block anything:
	alGetError();

	SilenceIKillYou = true;

	if (soundCache[a].playing) {
		if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
			debugOut( "Failed to stop source: %s\n",
						alureGetErrorString());
		}
	}
	if (! alureDestroyStream(soundCache[a].stream, 0, NULL)) {
		debugOut("Failed to destroy stream: %s\n",
					alureGetErrorString());
	}
	soundCache[a].stream = NULL;
	soundCache[a].fileLoaded = -1;

	SilenceIKillYou = false;
}
Beispiel #11
0
void playStream (int a, bool isMOD, bool loopy) {
	if (! soundOK) return;
	ALboolean ok;
	ALuint src;
	soundThing *st;
	void (*eos_callback)(void *userdata, ALuint source);

	if (isMOD) {
		st = &modCache[a];
		eos_callback = mod_eos_callback;
	}
	else {
		st = &soundCache[a];
		eos_callback = sound_eos_callback;
	}

	alGenSources(1, &src);
	if(alGetError() != AL_NO_ERROR)
	{
		debugOut( "Failed to create OpenAL source!\n");
		return;
	}

	if (isMOD) {
		alSourcef (src, AL_GAIN, (float) modLoudness * defVol / 256);
	} else {
		alSourcef (src, AL_GAIN, (float) soundCache[a].vol / 256);
	}

	if (loopy) {
		ok = alurePlaySourceStream(src, (*st).stream,
				NUM_BUFS, -1, eos_callback, &intpointers[a]);
	} else {
		ok = alurePlaySourceStream(src, (*st).stream,
				NUM_BUFS, 0, eos_callback, &intpointers[a]);
	}

	if(!ok) {
		debugOut("Failed to play stream: %s\n", alureGetErrorString());
		alDeleteSources(1, &src);
		if(alGetError() != AL_NO_ERROR)
		{
			debugOut("Failed to delete OpenAL source!\n");
		}
		(*st).playingOnSource = 0;
	} else {
		(*st).playingOnSource = src;
		(*st).playing = true;
	}
}
Beispiel #12
0
internal bool32
al_load_sound_file(uint32 *sourceID, uint32 *bufferID, char *filename)
{
    if ((*bufferID = alureCreateBufferFromFile(filename)) == AL_NONE)
    {
        al_log(true, "Alure failed to load %s. Alure error: %s\n", filename, alureGetErrorString());
        return false;
    }
    if (al_print_if_error("AL load sound: Failed to generate audio buffer\n")) return false;
    alSourcei(*sourceID, AL_BUFFER, *bufferID);
    if (al_print_if_error("AL load sound: Failed to bind source to buffer\n")) return false;
    al_set_default_source_values(*sourceID);
    return true;
}
Beispiel #13
0
void PlaySound(const std::string& name, float gain)
{
	const static ALfloat fz[] = { 0.0f, 0.0f, 0.0f };
	ALuint buf    = GetSound(name);
	ALuint source = GetFreeSource();
	LOG("Sound", LOG_NOTICE, "playing sound %s on channel %d", name.c_str(), source);
    const ALchar* err = alureGetErrorString();
	alSourcei(source, AL_BUFFER, buf);
	alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
	alSourcef(source, AL_GAIN, gain);
	alSourcefv(source, AL_POSITION, fz);
	alSourcefv(source, AL_VELOCITY, fz);
	alSourcePlay(source);
#ifndef NDEBUG
    if (alGetError())
        LOG("Sound", LOG_ERROR, "OpenAL error");
    err = alureGetErrorString();
    if (strcmp(err, "No error"))
    {
        LOG("Sound", LOG_ERROR, "ALURE error: %s", err);
        exit(1);
    }
#endif
}
Beispiel #14
0
void playSoundList(soundList *s) {
	if (soundOK) {

		cacheLoopySound = true;
		int a = cacheSound (s->sound);
		if (a == -1) {
			debugOut("Failed to cache sound!\n");
			return;
		}
		soundCache[a].looping = false;
		if (s->vol < 0)
			soundCache[a].vol = defSoundVol;
		else
			soundCache[a].vol = s->vol;
		s-> cacheIndex = a;

		ALboolean ok;
		ALuint src;
		soundThing *st;

		st = &soundCache[a];

		alGenSources(1, &src);
		if(alGetError() != AL_NO_ERROR)
		{
			debugOut("Failed to create OpenAL source!\n");
			return;
		}

		alSourcef (src, AL_GAIN, (float) soundCache[a].vol / 256);

		ok = alurePlaySourceStream(src, (*st).stream,
									   NUM_BUFS, 0, list_eos_callback, s);

		if(!ok) {
			debugOut("Failed to play stream: %s\n", alureGetErrorString());
			alDeleteSources(1, &src);
			if(alGetError() != AL_NO_ERROR)
			{
				debugOut("Failed to delete OpenAL source!\n");
			}
			(*st).playingOnSource = 0;
		} else {
			(*st).playingOnSource = src;
			(*st).playing = true;
		}
	}
}
Beispiel #15
0
static void mod_eos_callback(void *cacheIndex, ALuint source)
{
	int *a = (int*)cacheIndex;
	alDeleteSources(1, &source);
	if(alGetError() != AL_NO_ERROR)
	{
		debugOut("Failed to delete OpenAL source!\n");
	}
	modCache[*a].playingOnSource = 0;
	if (! alureDestroyStream(modCache[*a].stream, 0, NULL)) {
		debugOut("Failed to destroy stream: %s\n",
				alureGetErrorString());
	}
	modCache[*a].stream = NULL;
	modCache[*a].playing = false;
}
Beispiel #16
0
void huntKillSound (int filenum) {
	if (! soundOK) return;
	// Clear OpenAL errors to make sure they don't block anything:
	alGetError();

	int gotSlot = findInSoundCache (filenum);
	if (gotSlot == -1) return;

	SilenceIKillYou = true;

	if (soundCache[gotSlot].playing) {
		if (! alureStopSource(soundCache[gotSlot].playingOnSource, AL_TRUE)) {
			debugOut("Failed to stop source: %s\n",
						alureGetErrorString());
		}
	}

	SilenceIKillYou = false;
}
Beispiel #17
0
static ALuint GetSound(const std::string& name)
{
	BufferMap::iterator iter = sounds.find(name);
	if (iter != sounds.end())
		return iter->second;
	size_t length;
	ALubyte* data = GetSoundData("Sounds/" + name, length);
	ALuint buf = alureCreateBufferFromMemory(data, length);
	free(data);
	sounds.insert(std::make_pair(name, buf));
#ifndef NDEBUG
    const ALchar* err = alureGetErrorString();
    if (strcmp(err, "No error"))
    {
        LOG("Sound", LOG_ERROR, "GetSound: %s", err);
        exit(1);
    }
#endif
	return buf;
}
Beispiel #18
0
void PlayMusic(const std::string& name)
{
	StopMusic();
	size_t length;
	ALubyte* data = GetSoundData("Music/" + name, length);
	currentMusicName = name;
	currentMusicStream = alureCreateStreamFromStaticMemory(data, length, CHUNK_LENGTH, 2, musicBufs);
	alurePlaySourceStream(musicSource, currentMusicStream, 2, 1, MusicEndCallback, data);
	LOG("Sound", LOG_MESSAGE, "Music: %s", name.c_str());
	if (!data)
		LOG("Sound", LOG_WARNING, "failed to find music");
#ifndef NDEBUG
    if (alGetError())
        LOG("Sound", LOG_ERROR, "OpenAL error");
    const ALchar* err = alureGetErrorString();
    if (strcmp(err, "No error"))
    {
        LOG("Sound", LOG_ERROR, "ALURE error attempting to play song %s: %s", name.c_str(), err);
        exit(1);
    }
#endif
}
Beispiel #19
0
void Sound::run() {
    QFile audio_file(mResourcePath);
    if(audio_file.open(QIODevice::ReadOnly)) {
        QByteArray audio_data = audio_file.readAll();
        audio_file.close();

        ALuint src, buf;

        buf = alureCreateBufferFromMemory((const unsigned char*)audio_data.constData(), audio_data.size());

        alGenSources(1, &src);
        if(alGetError() != AL_NO_ERROR) {
            qDebug() << "Failed to create OpenAL source!";
        }

        if(!buf) {
            qDebug() << "Could not load sound: " << alureGetErrorString();
            alDeleteSources(1, &src);
        }

        alSourcei(src, AL_BUFFER, buf);
        alSourcef(src, AL_GAIN, 0.8f * mVolume);
        if(alurePlaySource(src, eos_callback, this) == AL_FALSE) {
            qDebug() << "Failed to start source!";
            alDeleteSources(1, &src);
            alDeleteBuffers(1, &buf);
        }

        while(!mIsDone) {
            alureSleep(0.125);
            alureUpdate();
        }

        alDeleteSources(1, &src);
        alDeleteBuffers(1, &buf);
    }
}
Beispiel #20
0
void Init(int frequency, int resolution, int sources)
{
	(void)resolution;
	--sources; // one spare source for music
	ALCint attribs[] = {
		ALC_FREQUENCY, frequency,
		/*ALC_MONO_SOURCES, sources,
		ALC_STEREO_SOURCES, 1,*/
		0
	};
	if (AL_FALSE == alureInitDevice(NULL, attribs)) {
        LOG("Sound", LOG_ERROR, "ALURE init failure");
        exit(1);
    }
    
	soundSources = new ALuint[sources];
	alGenSources(sources, soundSources);
	alGenSources(1, &musicSource);
	alGenBuffers(2, musicBufs);
	soundSourceCount = sources;
	alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
	alSpeedOfSound(1400.0);
	alDopplerFactor(0.7);
	alureUpdateInterval(0.03333f);
    
#ifndef NDEBUG
    if (alGetError())
        LOG("Sound", LOG_ERROR, "OpenAL init failure");
    const ALchar* err = alureGetErrorString();
    if (strcmp(err, "No error"))
    {
        LOG("Sound", LOG_ERROR, "ALURE init failure: %s", err);
        exit(1);
    }
#endif
}
Beispiel #21
0
void PlaySoundPositional(const std::string& name, vec2 pos, vec2 vel, float gain)
{
	ALfloat fpos[] = {pos.X(), pos.Y(), 0.0f};
	ALfloat fvel[] = {vel.X(), vel.Y(), 0.0f};
	ALuint buf    = GetSound(name);
	ALuint source = GetFreeSource();
	alSourcei(source, AL_BUFFER, buf);
	alSourcei(source, AL_SOURCE_RELATIVE, AL_FALSE);
	alSourcefv(source, AL_POSITION, fpos);
	alSourcefv(source, AL_VELOCITY, fvel);
	alSourcef(source, AL_REFERENCE_DISTANCE, 50.0);
	alSourcef(source, AL_GAIN, gain);
	alSourcePlay(source);
#ifndef NDEBUG
    if (alGetError())
        LOG("Sound", LOG_ERROR, "OpenAL error");
    const ALchar* err = alureGetErrorString();
    if (strcmp(err, "No error"))
    {
        LOG("Sound", LOG_ERROR, "ALURE error: %s", err);
        exit(1);
    }
#endif
}
Beispiel #22
0
int main () {
  if (!alureInitDevice(NULL, NULL)) {
    std::fprintf(stderr, "Failed to open OpenAL device: %s\n", alureGetErrorString());
    return 1;
  }

  alGenSources(1, &src);
  if (alGetError() != AL_NO_ERROR) {
    std::fprintf(stderr, "Failed to create OpenAL source!\n");
    alureShutdownDevice();
    return 1;
  }

  // Seeting Blip Buffer

  synth.treble_eq( -18.0f );

  synth.volume (0.80);
  synth.output (&blipbuf);

  // Init Blip Buffer with a buffer of 250ms (second paramter is time in ms)
  if ( blipbuf.set_sample_rate( SR, 1000 / 4 ) ) {
    std::fprintf(stderr, "Failed to create Blip Buffer! Our of Memory\n");
    alureShutdownDevice();
    return 1;
  }
  blipbuf.clock_rate( blipbuf.sample_rate() );
  blipbuf.bass_freq(300); // Equalization like a TV speaker

  stream = alureCreateStreamFromCallback (StreamCB, nullptr, AL_FORMAT_MONO16, SR, SR/2, 0, nullptr);

  if(!stream) {
    std::fprintf(stderr, "Error creating stream! %s\n",  alureGetErrorString());
    alDeleteSources(1, &src);

    alureShutdownDevice();
    return 1;
  }

  if (!alurePlaySourceStream(src, stream, 4, 0, eos_callback, NULL)) {
    std::fprintf(stderr, "Failed to play stream: %s\n", alureGetErrorString());
    isdone = 1;
  }

  alureUpdateInterval(0.005f); // Should be a independint thread  playing the stream

  while(!isdone) {
    freq -= 1;
    if (freq < 1) {
      freq = 600;
    }

    alureSleep(0.02f);
  }
  alureStopSource(src, AL_FALSE);

  alDeleteSources(1, &src);
  alureDestroyStream(stream, 0, NULL);

  alureShutdownDevice();
  return 0;
}
Beispiel #23
0
bool NSoundData::Load(std::string FileName)
{
    std::stringstream Message;
    ALenum Error = alGetError(); //Ensure all errors are cleared before making alure load the sound file, else it won't load.
    while (Error != AL_NO_ERROR)
    {
        switch(Error)
        {
            case AL_INVALID_NAME:
            {
                Message << "Invalid name parameter";
                break;
            }
            case AL_INVALID_ENUM:
            {
                Message << "Invalid parameter";
                break;
            }
            case AL_INVALID_VALUE:
            {
                Message << "Invalid enum parameter value";
                break;
            }
            case AL_INVALID_OPERATION:
            {
                Message << "Illegal call";
                break;
            }
            case AL_OUT_OF_MEMORY:
            {
                Message << "Unable to allocate memory";
                break;
            }
            default:
            {
                Message << "Unkown error";
                break;
            }
        }
        Error = alGetError();
    }
    GetGame()->GetLog()->Send("OPENAL",1,Message.str());
    NReadFile File = GetGame()->GetFileSystem()->GetReadFile(FileName);
    if (!File.Good())
    {
        GetGame()->GetLog()->Send("ALURE",1,"Failed to open " + FileName + " as a sound file, it doesn't exist!");
        return 1;
    }
    unsigned char* Data = new unsigned char[File.Size()];
    File.Read(Data,File.Size());
    ID = alureCreateBufferFromMemory(Data,File.Size());
    delete[] Data;
    if (ID == AL_NONE)
    {
        GetGame()->GetLog()->Send("ALURE",1,"Failed to open " + FileName + " as a sound file for reason: " + alureGetErrorString() + "!");
        return 1;
    }
    return 0;
}
Beispiel #24
0
int cacheSound (int f) {
	if (! soundOK) return -1;

	unsigned int chunkLength;
	int retval;
	bool loopy;

	loopy = cacheLoopySound;
	cacheLoopySound = false;

	setResourceForFatal (f);

	if (! soundOK) return 0;

	int a = findInSoundCache (f);
	if (a != -1) {
		if (soundCache[a].playing) {
			if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
				debugOut( "Failed to stop source: %s\n",
							alureGetErrorString());
			}
		}
		if (! alureRewindStream (soundCache[a].stream)) {
			debugOut( "Failed to rewind stream: %s\n",
						alureGetErrorString());
		}

		return a;
	}
	if (f == -2) return -1;
	a = findEmptySoundSlot ();
	freeSound (a);

	uint32_t length = openFileFromNum (f);
	if (! length) return -1;

	unsigned char * memImage;

	bool tryAgain = true;

	while (tryAgain) {
		memImage = (unsigned char*)loadEntireFileToMemory (bigDataFile, length);
		tryAgain = memImage == NULL;
		if (tryAgain) {
			if (! forceRemoveSound ()) {
				fatal (ERROR_SOUND_MEMORY_LOW);
				return -1;
			}
		}
	}

	chunkLength = 19200;

	// Small looping sounds need small chunklengths.
	if (loopy) {
		if (length < NUM_BUFS * chunkLength) {
			chunkLength = length / NUM_BUFS;
		}
	} else if (length < chunkLength) {
		chunkLength = length;
	}

	soundCache[a].stream = alureCreateStreamFromMemory(memImage, length, chunkLength, 0, NULL);

	delete memImage;

	if (soundCache[a].stream != NULL) {
		soundCache[a].fileLoaded = f;
		setResourceForFatal (-1);
		retval = a;
	} else {
		debugOut("Failed to create stream from sound: %s\n",
						alureGetErrorString());
		warning (ERROR_SOUND_ODDNESS);
		soundCache[a].stream = NULL;
		soundCache[a].playing = false;
		soundCache[a].playingOnSource = 0;
		soundCache[a].fileLoaded = -1;
		soundCache[a].looping = false;
		retval = -1;
	}

	return retval;
}
UBOOL UOpenALAudioSubsystem::Init()
{
	guard(UOpenALAudioSubsystem::Init);

	INT Rate = GetActualOutputRate();


	// OpenAL / ALURE initialization
	ALCint ContextAttrs[] = { ALC_FREQUENCY, Rate, 0 };
	if( alureInitDevice( NULL, ContextAttrs ) == AL_FALSE )
		appErrorf( TEXT("Couldn't initialize OpenAL: %s"), alureGetErrorString() );

	alDistanceModel( AL_LINEAR_DISTANCE_CLAMPED );
	CheckALErrorFlag( TEXT("alDistanceModel") );

	alDopplerFactor( DopplerFactor );
	CheckALErrorFlag( TEXT("alDopplerFactor") );

	// Metre per second to units per second, where units per meter is 52.5.
	// Taken from: http://wiki.beyondunreal.com/Legacy:General_Scale_And_Dimensions
	alSpeedOfSound( 343.3f * 52.5f );
	CheckALErrorFlag( TEXT("alSpeedOfSound") );

	ALuint* NewSources = new ALuint[NumSources + 1];
	Sources = new FAudioSource[NumSources];
	alGenSources( NumSources + 1, NewSources );
	CheckALErrorFlag( TEXT("alGenSources") );
	MusicSource = NewSources[0];
	for( INT i=0; i<NumSources; i++ )
		Sources[i].Id = NewSources[i+1];
	delete[] NewSources;

	// Fix the music source to 0 values
	alSource3f(	MusicSource, AL_POSITION,			0.f, 0.f, 0.f );
	alSource3f(	MusicSource, AL_VELOCITY,			0.f, 0.f, 0.f );
	alSource3f(	MusicSource, AL_DIRECTION,			0.f, 0.f, 0.f );
	alSourcef(	MusicSource, AL_ROLLOFF_FACTOR,		0.f );
	alSourcei(	MusicSource, AL_SOURCE_RELATIVE,	AL_TRUE );

	SetVolumes();
	CheckALErrorFlag( TEXT("SetVolumes") );


	// MikMod initialization
	//kipz - remove this because it breaks on new mikmod
	//MikMod_RegisterDriver( &MusicDriver );
	MikMod_RegisterAllDrivers();
	// Register only formats that are known to be supported by UT.
	// Taken from: http://wiki.beyondunreal.com/Music
	MikMod_RegisterLoader( &load_mod );
	MikMod_RegisterLoader( &load_s3m );
	MikMod_RegisterLoader( &load_stm );
	MikMod_RegisterLoader( &load_it  );
	MikMod_RegisterLoader( &load_xm  );
	MikMod_RegisterLoader( &load_far );
	MikMod_RegisterLoader( &load_669 );

	md_mixfreq = Rate;
	if ( HighQualityMusic )
		md_mode |= DMODE_HQMIXER;
	if( MikMod_Init( "" ) )
		appErrorf( TEXT("Couldn't initialize MikMod: %s"), MikMod_strerror( MikMod_errno ) );


	// Initialized!
	USound::Audio = this;
	UMusic::Audio = this;
	Initialized = 1;

	return 1;
	unguard;
}