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)
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 fillBufferAndQueue(buffers[i]);
38 StreamSoundSource::update()
41 alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
42 for(ALint i = 0; i < processed; ++i) {
44 alSourceUnqueueBuffers(source, 1, &buffer);
45 SoundManager::check_al_error("Couldn't unqueu audio buffer: ");
47 fillBufferAndQueue(buffer);
54 // we might have to restart the source if we had a buffer underrun
55 std::cerr << "Restarting audio source because of buffer underrun.\n";
61 alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
62 assert(queued == (ALint) STREAMFRAGMENTS);
65 if(fade_state == FadingOn) {
66 Uint32 ticks = SDL_GetTicks();
67 float time = (ticks - fade_start_ticks) / 1000.0;
68 if(time >= fade_time) {
70 fade_state = NoFading;
72 set_gain(time / fade_time);
74 } else if(fade_state == FadingOff) {
75 Uint32 ticks = SDL_GetTicks();
76 float time = (ticks - fade_start_ticks) / 1000.0;
77 if(time >= fade_time) {
79 fade_state = NoFading;
81 set_gain( (fade_time-time) / fade_time);
87 StreamSoundSource::set_fading(FadeState state, float fade_time)
89 this->fade_state = state;
90 this->fade_time = fade_time;
91 this->fade_start_ticks = SDL_GetTicks();
95 StreamSoundSource::fillBufferAndQueue(ALuint buffer)
98 char* bufferdata = new char[STREAMFRAGMENTSIZE];
101 bytesread += file->read(bufferdata + bytesread,
102 STREAMFRAGMENTSIZE - bytesread);
103 if(bytesread < STREAMFRAGMENTSIZE) {
106 } while(bytesread < STREAMFRAGMENTSIZE);
108 ALenum format = SoundManager::get_sample_format(file);
109 alBufferData(buffer, format, bufferdata, STREAMFRAGMENTSIZE, file->rate);
111 SoundManager::check_al_error("Couldn't refill audio buffer: ");
113 alSourceQueueBuffers(source, 1, &buffer);
114 SoundManager::check_al_error("Couldn't queue audio buffer: ");