6 #include "stream_sound_source.hpp"
7 #include "sound_manager.hpp"
8 #include "sound_file.hpp"
10 StreamSoundSource::StreamSoundSource()
11 : file(0), fade_state(NoFading), looping(false)
13 alGenBuffers(STREAMFRAGMENTS, buffers);
14 SoundManager::check_al_error("Couldn't allocate audio buffers: ");
17 StreamSoundSource::~StreamSoundSource()
20 alDeleteBuffers(STREAMFRAGMENTS, buffers);
21 SoundManager::check_al_error("Couldn't delete audio buffers: ");
25 StreamSoundSource::set_sound_file(SoundFile* newfile)
31 alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
32 for(size_t i = 0; i < STREAMFRAGMENTS - queued; ++i) {
33 if(fillBufferAndQueue(buffers[i]) == false)
39 StreamSoundSource::update()
42 alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
43 for(ALint i = 0; i < processed; ++i) {
45 alSourceUnqueueBuffers(source, 1, &buffer);
46 SoundManager::check_al_error("Couldn't unqueu audio buffer: ");
48 if(fillBufferAndQueue(buffer) == false)
53 if(processed == 0 || !looping)
56 // we might have to restart the source if we had a buffer underrun
57 std::cerr << "Restarting audio source because of buffer underrun.\n";
61 if(fade_state == FadingOn) {
62 Uint32 ticks = SDL_GetTicks();
63 float time = (ticks - fade_start_ticks) / 1000.0;
64 if(time >= fade_time) {
66 fade_state = NoFading;
68 set_gain(time / fade_time);
70 } else if(fade_state == FadingOff) {
71 Uint32 ticks = SDL_GetTicks();
72 float time = (ticks - fade_start_ticks) / 1000.0;
73 if(time >= fade_time) {
75 fade_state = NoFading;
77 set_gain( (fade_time-time) / fade_time);
83 StreamSoundSource::set_fading(FadeState state, float fade_time)
85 this->fade_state = state;
86 this->fade_time = fade_time;
87 this->fade_start_ticks = SDL_GetTicks();
91 StreamSoundSource::fillBufferAndQueue(ALuint buffer)
94 char* bufferdata = new char[STREAMFRAGMENTSIZE];
97 bytesread += file->read(bufferdata + bytesread,
98 STREAMFRAGMENTSIZE - bytesread);
100 if(bytesread < STREAMFRAGMENTSIZE) {
106 } while(bytesread < STREAMFRAGMENTSIZE);
109 ALenum format = SoundManager::get_sample_format(file);
110 alBufferData(buffer, format, bufferdata, bytesread, file->rate);
112 SoundManager::check_al_error("Couldn't refill audio buffer: ");
114 alSourceQueueBuffers(source, 1, &buffer);
115 SoundManager::check_al_error("Couldn't queue audio buffer: ");
118 // return false if there aren't more buffers to fill
119 return bytesread >= STREAMFRAGMENTSIZE;