void checkmusic(void) { unsigned int count; int count2; int queued; float vec[3]; if (!soundenabled) return; if (!config.sound) return; if (!option.sound) return; if (!option.music) game.songnum=-1; if (game.songnum>8) game.songnum=0; if (game.songnum!=game.currentsongnum) { if (game.currentsongnum!=-1) { alSourceStop(oggsource); alGetSourcei(oggsource,AL_BUFFERS_QUEUED,&queued); while (queued>0) { alSourceUnqueueBuffers(oggsource,1,&count); queued--; } ov_clear(&oggstream[0]); } if (game.songnum!=-1) { vorbiscallbacks.read_func=vorbisread; vorbiscallbacks.seek_func=vorbisseek; vorbiscallbacks.close_func=vorbisclose; vorbiscallbacks.tell_func=vorbistell; oggmemoryfile[game.songnum].dataread=0; if (ov_open_callbacks(&oggmemoryfile[game.songnum],&oggstream[0],NULL,0,vorbiscallbacks)>=0) { vorbisinfo=ov_info(&oggstream[0],-1); if (vorbisinfo->channels==1) oggformat=AL_FORMAT_MONO16; else oggformat=AL_FORMAT_STEREO16; streamogg(oggbuffer[0]); streamogg(oggbuffer[1]); alSourceQueueBuffers(oggsource,2,oggbuffer); vec[0]=0.0f; vec[1]=0.0f; vec[2]=0.0f; alSource3f(oggsource,AL_POSITION,vec[0],vec[1],vec[2]); alSource3f(oggsource,AL_VELOCITY,0.0f,0.0f,0.0f); alSourcef(oggsource,AL_REFERENCE_DISTANCE,10.0f); alSourcef(oggsource,AL_GAIN,0.3f*option.musicvolume); alSourcei(oggsource,AL_SOURCE_RELATIVE,AL_TRUE); alSourcePlay(oggsource); updateogg(); alSourcePlay(oggsource); game.currentsongnum=game.songnum; } else game.currentsongnum=-1; } else { game.currentsongnum=game.songnum; } } if (game.currentsongnum!=-1) { alGetSourcei(oggsource,AL_SOURCE_STATE,&count2); if (count2!=AL_PLAYING) alSourcePlay(oggsource); } }
void SoundSource::setPosition(float x, float y, float z) { alCheck(alSource3f(m_source, AL_POSITION, x, y, z)); }
CVoid COpenALSoundSource::SetSoundVelocity( CFloat* vel ) { alSource3f( m_soundSource, AL_VELOCITY, vel[0], vel[1], vel[2] ); }
void ChannelStream::Open( int channels, int bits, int samplerate ) { if (started) return; VERBOSE("ChannelStream Open"); if (channels == 1) { format = AL_FORMAT_MONO16; if (bits == 8) format = AL_FORMAT_MONO8; } else if (channels == 2) { format = AL_FORMAT_STEREO16; if (bits == 8) format = AL_FORMAT_STEREO8; } Check(); alGenBuffers(NUM_BUFFERS, buffers); Check("opengenbuf"); alGenSources(1, &source); Check("opengensource"); alSourcei(source, AL_BUFFER, AL_NONE); Check("buffer reset"); // Debug::Log("AUDIO: Opening Audio Channel: " + StringOf(samplerate) + "hz w/ " + StringOf(bits) + "bits w/ " + StringOf(channels) + " channels (ALformat:" + StringOf(format) +") SOURCE ID: " + StringOf(source)); Check("openbufferdata"); alSource3f(source, AL_POSITION, 0.0, 0.0, 0.0); /*alSource3f(source, AL_VELOCITY, 0.0, 0.0, 0.0); alSource3f(source, AL_DIRECTION, 0.0, 0.0, 0.0);*/ this->lastVol = 1.0; alSourcef(source, AL_GAIN, 1.0); alSourcef(source, AL_PITCH, 1.0); alSourcei(source, AL_LOOPING, AL_FALSE); Check("opensetsource"); alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE); alSourcei(source, AL_ROLLOFF_FACTOR, 0); Check("opensetsource2"); this->samplerate = samplerate; this->started = true; this->startBuffer = 0; this->startedPlaying = false; this->pausePos = 0; this->playOffset = 0; this->playStart = 0; }
void Source::velocity(const math::Vec3& val) { alSource3f(source, AL_VELOCITY, val.x, val.y, val.z);ALDEBUG_THROW; }
CVoid COpenALSoundSource::SetSoundPosition( CFloat* pos ) { alSource3f( m_soundSource, AL_POSITION, pos[0], pos[1], pos[2] ); }
void VoiceMessagesLoader::onLoad(AudioData *audio) { bool started = false; int32 audioindex = -1; Loader *l = 0; Loaders::iterator j = _loaders.end(); { QMutexLocker lock(&voicemsgsMutex); VoiceMessages *voice = audioVoice(); if (!voice) return; for (int32 i = 0; i < AudioVoiceMsgSimultaneously; ++i) { VoiceMessages::Msg &m(voice->_data[i]); if (m.audio != audio || !m.loading) continue; audioindex = i; j = _loaders.find(audio); if (j != _loaders.end() && (j.value()->fname != m.fname || j.value()->data.size() != m.data.size())) { delete j.value(); _loaders.erase(j); j = _loaders.end(); } if (j == _loaders.end()) { l = (j = _loaders.insert(audio, new Loader())).value(); l->fname = m.fname; l->data = m.data; int ret; if (m.data.isEmpty()) { l->file = op_open_file(m.fname.toUtf8().constData(), &ret); } else { l->file = op_open_memory((const unsigned char*)m.data.constData(), m.data.size(), &ret); } if (!l->file) { LOG(("Audio Error: op_open_file failed for '%1', data size '%2', error code %3").arg(m.fname).arg(m.data.size()).arg(ret)); m.state = VoiceMessageStopped; return loadError(j); } ogg_int64_t duration = op_pcm_total(l->file, -1); if (duration < 0) { LOG(("Audio Error: op_pcm_total failed to get full duration for '%1', data size '%2', error code %3").arg(m.fname).arg(m.data.size()).arg(duration)); m.state = VoiceMessageStopped; return loadError(j); } m.duration = duration; m.skipStart = 0; m.skipEnd = duration; m.position = 0; m.started = 0; started = true; } else { if (!m.skipEnd) continue; l = j.value(); } break; } } if (j == _loaders.end()) { LOG(("Audio Error: trying to load part of audio, that is not playing at the moment")); emit error(audio); return; } if (started) { l->pcm_offset = op_pcm_tell(l->file); l->pcm_print_offset = l->pcm_offset - AudioVoiceMsgFrequency; } bool finished = false; DEBUG_LOG(("Audio Info: reading buffer for file '%1', data size '%2', current pcm_offset %3").arg(l->fname).arg(l->data.size()).arg(l->pcm_offset)); QByteArray result; int64 samplesAdded = 0; while (result.size() < AudioVoiceMsgBufferSize) { opus_int16 pcm[AudioVoiceMsgFrequency * AudioVoiceMsgChannels]; int ret = op_read_stereo(l->file, pcm, sizeof(pcm) / sizeof(*pcm)); if (ret < 0) { { QMutexLocker lock(&voicemsgsMutex); VoiceMessages *voice = audioVoice(); if (voice) { VoiceMessages::Msg &m(voice->_data[audioindex]); if (m.audio == audio) { m.state = VoiceMessageStopped; } } } LOG(("Audio Error: op_read_stereo failed, error code %1").arg(ret)); return loadError(j); } int li = op_current_link(l->file); if (li != l->prev_li) { const OpusHead *head = op_head(l->file, li); const OpusTags *tags = op_tags(l->file, li); for (int32 ci = 0; ci < tags->comments; ++ci) { const char *comment = tags->user_comments[ci]; if (opus_tagncompare("METADATA_BLOCK_PICTURE", 22, comment) == 0) { OpusPictureTag pic; int err = opus_picture_tag_parse(&pic, comment); if (err >= 0) { opus_picture_tag_clear(&pic); } } } if (!op_seekable(l->file)) { l->pcm_offset = op_pcm_tell(l->file) - ret; } } if (li != l->prev_li || l->pcm_offset >= l->pcm_print_offset + AudioVoiceMsgFrequency) { l->pcm_print_offset = l->pcm_offset; } l->pcm_offset = op_pcm_tell(l->file); if (!ret) { DEBUG_LOG(("Audio Info: read completed")); finished = true; break; } result.append((const char*)pcm, sizeof(*pcm) * ret * AudioVoiceMsgChannels); l->prev_li = li; samplesAdded += ret; { QMutexLocker lock(&voicemsgsMutex); VoiceMessages *voice = audioVoice(); if (!voice) return; VoiceMessages::Msg &m(voice->_data[audioindex]); if (m.audio != audio || !m.loading || m.fname != l->fname || m.data.size() != l->data.size()) { LOG(("Audio Error: playing changed while loading")); m.state = VoiceMessageStopped; return loadError(j); } } } QMutexLocker lock(&voicemsgsMutex); VoiceMessages *voice = audioVoice(); if (!voice) return; VoiceMessages::Msg &m(voice->_data[audioindex]); if (m.audio != audio || !m.loading || m.fname != l->fname || m.data.size() != l->data.size()) { LOG(("Audio Error: playing changed while loading")); m.state = VoiceMessageStopped; return loadError(j); } if (started) { if (m.source) { alSourceStop(m.source); for (int32 i = 0; i < 3; ++i) { if (m.samplesCount[i]) { alSourceUnqueueBuffers(m.source, 1, m.buffers + i); m.samplesCount[i] = 0; } } m.nextBuffer = 0; } } if (samplesAdded) { if (!m.source) { alGenSources(1, &m.source); alSourcef(m.source, AL_PITCH, 1.f); alSourcef(m.source, AL_GAIN, 1.f); alSource3f(m.source, AL_POSITION, 0, 0, 0); alSource3f(m.source, AL_VELOCITY, 0, 0, 0); alSourcei(m.source, AL_LOOPING, 0); } if (!m.buffers[m.nextBuffer]) alGenBuffers(3, m.buffers); if (!_checkALError()) { m.state = VoiceMessageStopped; return loadError(j); } if (m.samplesCount[m.nextBuffer]) { alSourceUnqueueBuffers(m.source, 1, m.buffers + m.nextBuffer); m.skipStart += m.samplesCount[m.nextBuffer]; } m.samplesCount[m.nextBuffer] = samplesAdded; alBufferData(m.buffers[m.nextBuffer], AL_FORMAT_STEREO16, result.constData(), result.size(), AudioVoiceMsgFrequency); alSourceQueueBuffers(m.source, 1, m.buffers + m.nextBuffer); m.skipEnd -= samplesAdded; m.nextBuffer = (m.nextBuffer + 1) % 3; if (!_checkALError()) { m.state = VoiceMessageStopped; return loadError(j); } } else { finished = true; } if (finished) { m.skipEnd = 0; m.duration = m.skipStart + m.samplesCount[0] + m.samplesCount[1] + m.samplesCount[2]; } m.loading = false; if (m.state == VoiceMessageResuming || m.state == VoiceMessagePlaying || m.state == VoiceMessageStarting) { ALint state = AL_INITIAL; alGetSourcei(m.source, AL_SOURCE_STATE, &state); if (_checkALError()) { if (state != AL_PLAYING) { alSourcePlay(m.source); emit needToCheck(); } } } }
void Source::direction(const math::Vec3& val) { alSource3f(source, AL_DIRECTION, val.x, val.y, val.z);ALDEBUG_THROW; }
//----------------------------------------------------------------------------- bool MusicOggStream::load(const std::string& filename) { if (isPlaying()) stopMusic(); m_error = true; m_fileName = filename; if(m_fileName=="") return false; m_oggFile = fopen(m_fileName.c_str(), "rb"); if(!m_oggFile) { printf("Loading Music: %s failed (fopen returned NULL)\n", m_fileName.c_str()); return false; } #if defined( WIN32 ) || defined( WIN64 ) const int result = ov_open_callbacks((void *)m_oggFile, &m_oggStream, NULL, 0, OV_CALLBACKS_DEFAULT); #else const int result = ov_open(m_oggFile, &m_oggStream, NULL, 0); #endif if (result < 0) { fclose(m_oggFile); const char* errorMessage; switch (result) { case OV_EREAD: errorMessage = "OV_EREAD"; break; case OV_ENOTVORBIS: errorMessage = "OV_ENOTVORBIS"; break; case OV_EVERSION: errorMessage = "OV_EVERSION"; break; case OV_EBADHEADER: errorMessage = "OV_EBADHEADER"; break; case OV_EFAULT: errorMessage = "OV_EFAULT"; break; default: errorMessage = "Unknown Error"; } printf("Loading Music: %s failed : ov_open returned error code %i (%s)\n", m_fileName.c_str(), result, errorMessage); return false; } m_vorbisInfo = ov_info(&m_oggStream, -1); if (m_vorbisInfo->channels == 1) nb_channels = AL_FORMAT_MONO16; else nb_channels = AL_FORMAT_STEREO16; alGenBuffers(2, m_soundBuffers); if (check("alGenBuffers") == false) return false; alGenSources(1, &m_soundSource); if (check("alGenSources") == false) return false; alSource3f(m_soundSource, AL_POSITION, 0.0, 0.0, 0.0); alSource3f(m_soundSource, AL_VELOCITY, 0.0, 0.0, 0.0); alSource3f(m_soundSource, AL_DIRECTION, 0.0, 0.0, 0.0); alSourcef (m_soundSource, AL_ROLLOFF_FACTOR, 0.0 ); alSourcef (m_soundSource, AL_GAIN, 1.0 ); alSourcei (m_soundSource, AL_SOURCE_RELATIVE, AL_TRUE ); m_error=false; return true; } // load
void lime_al_source3f (int source, int param, float value1, float value2, float value3) { alSource3f (source, param, value1, value2, value3); }
void NzSoundEmitter::SetVelocity(float velX, float velY, float velZ) { alSource3f(m_source, AL_VELOCITY, velX, velY, velZ); }
void NzSoundEmitter::SetPosition(float x, float y, float z) { alSource3f(m_source, AL_POSITION, x, y, z); }
void LightningWeapon::fire() { // Get a particle. Particle* p = gWorld->getParticleSystem()->addParticleWithBody(2, false); if(!p) return; // Get player. Player* player = gWorld->getPlayer(); // Set basic particle properties. p->mCallback = lightningBulletParticleCallback; p->mAlpha = 1.0f; // Choose some numbers. float f = 10.0; float r = 1.0/f - ((rand()%100)/(f*90)) ; // float initialRotation = player->mFireDirection; float initialRotation = player->mTurret.mRotation - M_PI/2.0f; // Setup image. int i=rand()%PARTICLE_LIGHTNING_COUNT; float velocity = 130; if(i) { velocity+=100+(rand()%100); } p->mImage.setImage(gImageLibrary->getImage(PARTICLE_LIGHTNING_00 + i)); p->mImage.mCenter = player->mTurretTip; p->mImage.mRotation = initialRotation + r; p->mImage.makeDirty(); // Properties about lightning bullet particles. p->mBody->mProperties = kPlayerBulletCollisionProperties; p->mBody->mCollideProperties = kEnemyCollisionProperties | kPlayerBarrierCollisionProperties; p->mBody->mBodyCallback = lightningBulletCollisionCallback; p->mBody->mShapeCallback = lightningBulletShapeCollisionCallback; p->mBody->mDamping = 0; p->mBody->mRadius = 8; p->mBody->mMass = 10; p->mBody->mCenter = p->mImage.mCenter + Vector2(8, 0) * Transform2::createRotation(initialRotation+r); p->mBody->mVelocity = player->mBody->mVelocity + Vector2(velocity, 0) * Transform2::createRotation(initialRotation+r); // Get a particle. p = gWorld->getParticleSystem()->addParticle(2, false); if(!p) return; // Set basic particle properties. p->mCallback = lightningGlowParticleCallback; p->mAlpha = 0.6f; // Setup image. p->mImage.setImage(gImageLibrary->getImage(PARTICLE_LIGHTNING_GLOW_00)); p->mImage.mCenter = player->mTurretTip; p->mImage.mRotation = initialRotation + (r*4); p->mImage.makeDirty(); LightningWeaponParticleData* data = (LightningWeaponParticleData*)(p->mData); data->mWeapon = this; ++mParticleCount; if(mParticleCount == 1) { gAudioLibrary->playAudioInstance(mAudio, PLAY_FOREVER, false); } if(gAudioLibrary->getAudioEnabled()) { alSource3f(mAudio->mSource, AL_POSITION, p->mImage.mCenter.x, p->mImage.mCenter.y, 0.0f); } }
void Grabber::run () { // Create the interface pcl::Grabber* interface = new pcl::OpenNIGrabber(); // Connect rgbd callback boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float constant)> rgbd =\ boost::bind (&Grabber::rgbd_cb_, this, _1,_2,_3); boost::signals2::connection c = interface->registerCallback (rgbd); // Start the interface Sleep(500); printf("Starting Interface\n"); interface->start(); printf("Started Interface\n"); while(!newImages){ Sleep(10); } printf("There is an incoming image\n"); // Connect keyListener callback boost::thread keyListen(&Grabber::keyListener, this); IplImage ipl_img; CvScalar color = CV_RGB(255, 0, 0); int num_segs; std::vector<ncmec::Segment> segs; ipl_img = frameBGR; ncmec::SuperPixel* sp = new ncmec::SuperPixel(&ipl_img); const int* seg_map; seg_map = new int[640*480]; int drawing = 1; // Thread runs forever until stop while (control.running) { if(newImages){ boost::progress_timer timer; converting = true; //frameBGR = cv::imread("C:\\Users\\Robrecht\\3DVITA\\3DVITA_src\\Segmentation\\malevich.jpg", CV_LOAD_IMAGE_COLOR); //cv::resize(frameBGR, frameBGR, cv::Size(640,480)); // Calculate texturedness by comparing to local area cv::Mat edges; cv::Mat frameGrey, frameGreyBlur; cv::cvtColor(frameBGR, frameGrey, CV_BGR2GRAY); cv::blur(frameGrey, frameGreyBlur, cv::Size(9,9)); edges = abs(frameGrey-frameGreyBlur); // imshow("TEST", edges); // cv::waitKey(33); frameGrey.release(); frameGreyBlur.release(); ipl_img = frameBGR; sp->updateImage(&ipl_img); int clusters = 64; if(tmp_clusters>31) clusters = tmp_clusters; else clusters = 32; sp->SegmentNumber(clusters, m); segs = sp->segments(); num_segs = sp->num_segments(); seg_map = sp->segmentation_map(); // Move segmentation map into a Mat structure for(int i=0; i<480*640; i++){ frameS.data[i] = seg_map[i]; } cv::Mat M; // Calculate mean HSV for each segment frameBGR.release(); frameBGR = cv::Mat(480,640,CV_8UC3, cv::Scalar(0,0,0,0)); int notes[12] = {30,32,33,35,37,39,40,42,44,45,47,49}; std::vector<std::vector<int> > slices; slices.resize(20); int num_seg = sp->num_segments(); std::vector<cv::Mat> hsv_planes; cv::split(frameHSV, hsv_planes); #ifdef FREQHISTO //cv::Mat histograms = cv::Mat::zeros(num_seg, 6, CV_32S); cv::Mat histograms = cv::Mat::zeros(num_seg, 6, CV_32F); for(int i=0; i<480*640; i++){ int x = hsv_planes[0].data[i]; int segNo = frameS.data[i]; /* if(x<15) histograms.at<int>(segNo,0)++; else if(x<45) histograms.at<int>(segNo,1)++; else if(x<90) histograms.at<int>(segNo,2)++; else if(x<180) histograms.at<int>(segNo,3)++; else if(x<270) histograms.at<int>(segNo,4)++; else if(x<315) histograms.at<int>(segNo,5)++; else histograms.at<int>(segNo,0)++; */ if(x>245) std::cout << x << std::endl; x = (x/255.f)*360; if(x<11 || x >355){ // RED G4 histograms.at<float>(segNo,0)++; }else if(x<51){ float alpha = 1-((x-11)/(50.f-11.f)); histograms.at<float>(segNo,0) += alpha; histograms.at<float>(segNo,1) += (1-alpha); }else if(x<61){ // Yellow Bb4 histograms.at<float>(segNo,1)++; }else if(x<81){ float alpha = 1-((x-61)/(80.f-61.f)); histograms.at<float>(segNo,1) += alpha; histograms.at<float>(segNo,2) += (1-alpha); }else if(x<141){ // Green C5 histograms.at<float>(segNo,2)++; }else if(x<221){ float alpha = 1-((x-141)/(220.f-141.f)); histograms.at<float>(segNo,2) += alpha; histograms.at<float>(segNo,3) += (1-alpha); }else if(x<241){ // Blue D#5 histograms.at<float>(segNo,3)++; }else if(x<331){ float alpha = 1-((x-241)/(330.f-241.f)); histograms.at<float>(segNo,3) += alpha; histograms.at<float>(segNo,5) += (1-alpha); }else if(x<346){ // Pink F5 histograms.at<float>(segNo,5)++; }else{ float alpha = 1-((x-346)/(355.f-346.f)); histograms.at<float>(segNo,5) += alpha; histograms.at<float>(segNo,0) += (1-alpha); } // * 0 = Red 392 G4 // * 30 = Orange 440 A4 // * 60 = Yellow 466.16 Bb4 // * 90 = Chartreuse 494 B4 // * 120 = Green 523.25 C5 // * 150 = Green 523.25 // * 180 = Cyan 554.37 Db5 // * 210 = Blue 587.33 D5 // * 240 = Blue 587.33 // * 270 = Violet 659.25 E5 // * 300 = Magenta 698.46 F5 // * 330 = Red } #else std::vector<float> cosSum (num_seg, 0.0); std::vector<float> sinSum (num_seg, 0.0); std::vector<float> hueMean (num_seg, 0.0); for(int i=0; i<480*640; i++){ //printf("%i -> hsv_val: %i, %f, %f, %f\n", frameS.data[i], hsv_planes[0].data[i], hsv_planes[0].data[i]/255.f, hsv_planes[0].data[i]/255.f, ((float)hsv_planes[0].data[i]/255.f)*360.f); //cosSum[frameS.data[i]] += cos((((float)hsv_planes[0].data[i]/255.f)*360.f)*M_PI/180.f); //sinSum[frameS.data[i]] += sin((((float)hsv_planes[0].data[i]/255.f)*360.f)*M_PI/180.f); cosSum[frameS.data[i]] += cos((float)hsv_planes[0].data[i]*M_PI/180.0); sinSum[frameS.data[i]] += sin((float)hsv_planes[0].data[i]*M_PI/180.0); } for(int i =0; i<hueMean.size(); i++){ hueMean[i] = atan2(sinSum[i], cosSum[i])*180.0/M_PI; } cosSum.clear(); sinSum.clear(); #endif hsv_planes.clear(); int maxTex = 0; for(int i=0; i<std::min(clusters, sp->num_segments()); i++){ cv::Scalar hsv = mean(frameHSV, frameS==i); //cv::Mat tmpEdges; //edges.copyTo(tmpEdges, frameS==i); //cv::Scalar texture = cv::sum(tmpEdges); cv::Scalar texture = mean(edges, frameS==i); //tmpEdges.release(); // std::cout << "cluster " << i << " has sum of " << texture[0] << " and Max is " << maxTex << std::endl; #ifndef FREQHISTO M = cv::Mat(480, 640, CV_8UC3, cv::Scalar(hueMean[i], hsv[1], hsv[2])); #else M = cv::Mat(480, 640, CV_8UC3, hsv); #endif // Create Sound float depth = frameD.at<float>(segs[i].center); if(!control.depth) depth = 2.f+ (sqrt( (pow(segs[i].center.x-320.f, 2) + pow(segs[i].center.y-240.f,2)))/100.f); if(depth<0.3 || depth!=depth){ // objects[i].location[2] = depth; } else{ depth = std::max(0.1f, depth); float location[3] = {(int)(segs[i].center.x)*depth* constant_c, segs[i].center.y*depth*constant_c, depth}; audio::audioParams params; ///* Hue Names: http://www.procato.com/rgb+index/ // * 0 = Red 392 G4 // * 30 = Orange 440 A4 // * 60 = Yellow 466.16 Bb4 // * 90 = Chartreuse 494 B4 // * 120 = Green 523.25 C5 // * 150 = Green 523.25 // * 180 = Cyan 554.37 Db5 // * 210 = Blue 587.33 D5 // * 240 = Blue 587.33 // * 270 = Violet 659.25 E5 // * 300 = Magenta 698.46 F5 // * 330 = Red // * 360 = Red // * Frequency adjusted to scale based on A4=440.f // */ //float tones[13] = {392, 440, 466.16, 493.88, 523.25, 523.25, 554.37, 587.33, 587.33, 659.25, 698.46, 392, 392}; float tones[6] = {392, 466.16, 523.25, 554.37, 587.33, 698.46}; //params.freq = tones[(int)((hsv[0]/255)*7)]; if(control.verbose){ #ifndef FREQHISTO printf("%i,\t %f,\t %i,\t %f\n", i, hueMean[i], (int)(hueMean[i]/360.0)*6, tones[(int)(((hueMean[i]/360.0))*6)]); #endif } float brightness = 1.0f; if(((int)((hsv[2]/255.f)*2))==0) brightness = 0.5f; else if(((int)((hsv[2]/255.f)*2))==2) brightness = 2.0f; params.brightness = brightness; #ifndef FREQHISTO params.freq = tones[(int)(((hueMean[i]/360.0))*6)]*brightness; #else histograms.row(i).copyTo(params.freqMat); #endif params.dampThres = hsv[1]/255; //params.freqMat = histograms; params.texture = texture[0]/50.f; params.attack = 0.05; params.decay = 0.4; params.release = 0.45; params.sustain = 0.9; depth = std::min(std::max(depth, 0.5f), 8.0f); slices[std::min(19, (int)(depth*2))].push_back(AE.sounds.size()); AE.createSound(params, location); } M.copyTo(frameBGR, frameS==i); M.release(); } if(control.verbose) printf("playing sounds\n"); cv::cvtColor(frameBGR, frameBGR, CV_HSV2BGR); // While playing sounds, wait while(playing && control.running){ Sleep(10); } //boost::progress_timer timer2; // Copy image, slices, sounds, segments into player tmpFrame = frameBGR.clone(); std::vector<std::vector<int> > tmpSlices; tmpSlices.resize(slices.size()); for(int i = 0; i<slices.size(); i++) for(int j = 0; j<slices[i].size(); j++) tmpSlices[i].push_back(slices[i][j]); std::vector<cv::Point> tmpCenters; for(int i=0; i<segs.size(); i++) tmpCenters.push_back(cv::Point(segs[i].center.x, segs[i].center.y)); std::vector<audio::audioObject> tmpSounds; for(int i = 0; i<AE.sounds.size(); i++){ audio::audioObject tmpSound; // Create a source alGenSources( 1, &tmpSound.source ); alSourcef( tmpSound.source, AL_PITCH, 1. ); alSourcef( tmpSound.source, AL_GAIN, 1. ); alSource3f( tmpSound.source, AL_POSITION, AE.sounds[i].location[0], AE.sounds[i].location[1], AE.sounds[i].location[2] ); alSource3f( tmpSound.source, AL_VELOCITY, 0.,0.,0. ); alSourcei( tmpSound.source, AL_LOOPING, AL_FALSE ); alGenBuffers( 1, &tmpSound.buffer ); //audioData = data; tmpSound.location[0] = AE.sounds[i].location[0]; tmpSound.location[1] = AE.sounds[i].location[1]; tmpSound.location[2] = AE.sounds[i].location[2]; tmpSound.data = new short[44100]; for(int j = 0; j<44100 ; j++) tmpSound.data[j] = AE.sounds[i].data[j]; alBufferData(tmpSound.buffer, AL_FORMAT_MONO16, tmpSound.data, 44100, 44100 ); alSourcei( tmpSound.source, AL_BUFFER, tmpSound.buffer ); tmpSounds.push_back(tmpSound); //tmpSounds.push_back(AE.sounds[i]); } updateImage = true; boost::thread(&Grabber::playSounds, this, tmpSlices, tmpSounds, tmpCenters, sp->num_segments()); // Remove stuff for(int i = 0; i<AE.sounds.size(); i++){ alDeleteSources( 1, &AE.sounds[i].source ); alDeleteBuffers( 1, &AE.sounds[i].buffer ); delete [] AE.sounds[i].data; } AE.sounds.clear(); slices.clear(); #ifndef FREQHISTO hueMean.clear(); #endif converting=false; newImages=false; cv::waitKey(1); } segs.clear(); } sp->~SuperPixel(); interface->stop (); }
void audioInit() { if (audioDevice) return; audioDevice = alcOpenDevice(NULL); if (!audioDevice) { LOG(("Audio Error: default sound device not present.")); return; } ALCint attributes[] = { ALC_STEREO_SOURCES, 8, 0 }; audioContext = alcCreateContext(audioDevice, attributes); alcMakeContextCurrent(audioContext); if (!_checkALCError()) return audioFinish(); ALfloat v[] = { 0.f, 0.f, -1.f, 0.f, 1.f, 0.f }; alListener3f(AL_POSITION, 0.f, 0.f, 0.f); alListener3f(AL_VELOCITY, 0.f, 0.f, 0.f); alListenerfv(AL_ORIENTATION, v); alDistanceModel(AL_NONE); alGenSources(1, ¬ifySource); alSourcef(notifySource, AL_PITCH, 1.f); alSourcef(notifySource, AL_GAIN, 1.f); alSource3f(notifySource, AL_POSITION, 0, 0, 0); alSource3f(notifySource, AL_VELOCITY, 0, 0, 0); alSourcei(notifySource, AL_LOOPING, 0); alGenBuffers(1, ¬ifyBuffer); if (!_checkALError()) return audioFinish(); QFile notify(st::newMsgSound); if (!notify.open(QIODevice::ReadOnly)) return audioFinish(); QByteArray blob = notify.readAll(); const char *data = blob.constData(); if (blob.size() < 44) return audioFinish(); if (*((const uint32*)(data + 0)) != 0x46464952) return audioFinish(); // ChunkID - "RIFF" if (*((const uint32*)(data + 4)) != uint32(blob.size() - 8)) return audioFinish(); // ChunkSize if (*((const uint32*)(data + 8)) != 0x45564157) return audioFinish(); // Format - "WAVE" if (*((const uint32*)(data + 12)) != 0x20746d66) return audioFinish(); // Subchunk1ID - "fmt " uint32 subchunk1Size = *((const uint32*)(data + 16)), extra = subchunk1Size - 16; if (subchunk1Size < 16 || (extra && extra < 2)) return audioFinish(); if (*((const uint16*)(data + 20)) != 1) return audioFinish(); // AudioFormat - PCM (1) uint16 numChannels = *((const uint16*)(data + 22)); if (numChannels != 1 && numChannels != 2) return audioFinish(); uint32 sampleRate = *((const uint32*)(data + 24)); uint32 byteRate = *((const uint32*)(data + 28)); uint16 blockAlign = *((const uint16*)(data + 32)); uint16 bitsPerSample = *((const uint16*)(data + 34)); if (bitsPerSample % 8) return audioFinish(); uint16 bytesPerSample = bitsPerSample / 8; if (bytesPerSample != 1 && bytesPerSample != 2) return audioFinish(); if (blockAlign != numChannels * bytesPerSample) return audioFinish(); if (byteRate != sampleRate * blockAlign) return audioFinish(); if (extra) { uint16 extraSize = *((const uint16*)(data + 36)); if (uint32(extraSize + 2) != extra) return audioFinish(); if (uint32(blob.size()) < 44 + extra) return audioFinish(); } if (*((const uint32*)(data + extra + 36)) != 0x61746164) return audioFinish(); // Subchunk2ID - "data" uint32 subchunk2Size = *((const uint32*)(data + extra + 40)); if (subchunk2Size % (numChannels * bytesPerSample)) return audioFinish(); uint32 numSamples = subchunk2Size / (numChannels * bytesPerSample); if (uint32(blob.size()) < 44 + extra + subchunk2Size) return audioFinish(); data += 44 + extra; ALenum format = 0; switch (bytesPerSample) { case 1: switch (numChannels) { case 1: format = AL_FORMAT_MONO8; break; case 2: format = AL_FORMAT_STEREO8; break; } break; case 2: switch (numChannels) { case 1: format = AL_FORMAT_MONO16; break; case 2: format = AL_FORMAT_STEREO16; break; } break; } if (!format) return audioFinish(); alBufferData(notifyBuffer, format, data, subchunk2Size, sampleRate); alSourcei(notifySource, AL_BUFFER, notifyBuffer); if (!_checkALError()) return audioFinish(); voicemsgs = new VoiceMessages(); }
void Sound::SetPosition(vec3 pos) { alSource3f(id, AL_POSITION, pos.x, pos.y, pos.z); }
//============================================================================ void plDSoundBuffer::SetVelocity(float x, float y, float z) { alSource3f(source, AL_VELOCITY, 0, 0, 0); // no doppler shift alGetError(); }
void Source::position(const math::Vec3& val) { alSource3f(source, AL_POSITION, val.x, val.y, val.z);ALDEBUG_THROW; }
//============================================================================ void plDSoundBuffer::SetConeOrientation(float x, float y, float z) { alSource3f(source, AL_DIRECTION, x, y, -z); // negate z coord, since openal uses opposite handedness alGetError(); }
void Source::setAttribute_3f(unsigned int attrib,float v1,float v2,float v3){ alSource3f( sourceId,static_cast<ALenum>(attrib),v1,v2,v3 ); }
int main(int argc, char **argv) { ALCdevice *device; ALuint source, buffer; const char *soundname; const char *hrtfname; ALCint hrtf_state; ALCint num_hrtf; ALdouble angle; ALenum state; /* Print out usage if no file was specified */ if(argc < 2 || (strcmp(argv[1], "-hrtf") == 0 && argc < 4)) { fprintf(stderr, "Usage: %s [-hrtf <name>] <soundfile>\n", argv[0]); return 1; } /* Initialize OpenAL with the default device, and check for HRTF support. */ if(InitAL() != 0) return 1; if(strcmp(argv[1], "-hrtf") == 0) { hrtfname = argv[2]; soundname = argv[3]; } else { hrtfname = NULL; soundname = argv[1]; } device = alcGetContextsDevice(alcGetCurrentContext()); if(!alcIsExtensionPresent(device, "ALC_SOFT_HRTF")) { fprintf(stderr, "Error: ALC_SOFT_HRTF not supported\n"); CloseAL(); return 1; } /* Define a macro to help load the function pointers. */ #define LOAD_PROC(d, x) ((x) = alcGetProcAddress((d), #x)) LOAD_PROC(device, alcGetStringiSOFT); LOAD_PROC(device, alcResetDeviceSOFT); #undef LOAD_PROC /* Enumerate available HRTFs, and reset the device using one. */ alcGetIntegerv(device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf); if(!num_hrtf) printf("No HRTFs found\n"); else { ALCint attr[5]; ALCint index = -1; ALCint i; printf("Available HRTFs:\n"); for(i = 0; i < num_hrtf; i++) { const ALCchar *name = alcGetStringiSOFT(device, ALC_HRTF_SPECIFIER_SOFT, i); printf(" %d: %s\n", i, name); /* Check if this is the HRTF the user requested. */ if(hrtfname && strcmp(name, hrtfname) == 0) index = i; } i = 0; attr[i++] = ALC_HRTF_SOFT; attr[i++] = ALC_TRUE; if(index == -1) { if(hrtfname) printf("HRTF \"%s\" not found\n", hrtfname); printf("Using default HRTF...\n"); } else { printf("Selecting HRTF %d...\n", index); attr[i++] = ALC_HRTF_ID_SOFT; attr[i++] = index; } attr[i] = 0; if(!alcResetDeviceSOFT(device, attr)) printf("Failed to reset device: %s\n", alcGetString(device, alcGetError(device))); } /* Check if HRTF is enabled, and show which is being used. */ alcGetIntegerv(device, ALC_HRTF_SOFT, 1, &hrtf_state); if(!hrtf_state) printf("HRTF not enabled!\n"); else { const ALchar *name = alcGetString(device, ALC_HRTF_SPECIFIER_SOFT); printf("HRTF enabled, using %s\n", name); } fflush(stdout); /* Load the sound into a buffer. */ buffer = LoadSound(soundname); if(!buffer) { CloseAL(); return 1; } /* Create the source to play the sound with. */ source = 0; alGenSources(1, &source); alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE); alSource3f(source, AL_POSITION, 0.0f, 0.0f, -1.0f); alSourcei(source, AL_BUFFER, buffer); assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Play the sound until it finishes. */ angle = 0.0; alSourcePlay(source); do { al_nssleep(10000000); /* Rotate the source around the listener by about 1/4 cycle per second. * Only affects mono sounds. */ angle += 0.01 * M_PI * 0.5; alSource3f(source, AL_POSITION, (ALfloat)sin(angle), 0.0f, -(ALfloat)cos(angle)); alGetSourcei(source, AL_SOURCE_STATE, &state); } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING); /* All done. Delete resources, and close OpenAL. */ alDeleteSources(1, &source); alDeleteBuffers(1, &buffer); CloseAL(); return 0; }
CVoid COpenALSoundSource::SetSoundPosition( ) { alSource3f( m_soundSource, AL_POSITION, 0.0f, 0.0f, 1.0f ); }
void ChannelStream::SetPan( float pan ) { if (started) alSource3f(source,AL_POSITION,pan,0.0,0.0); }
size_t SonicDog::addObject( float x, float z, obj_t type ) { // instantiate the source and buffer for this sound source SoundSrc *src = new SoundSrc; src->id = object_id_; src->once = false; src->x = x; src->z = z; src->pause = 1.5; alGetError(); alGenSources( 1, &(src->source) ); checkError( "alGenSources", AL ); switch ( type ) { case BEAC: { // src->buffer = alutCreateBufferWaveform( ALUT_WAVEFORM_WHITENOISE, 500.0f, 0.0f, 0.5f ); alutGetError(); src->buffer = alutCreateBufferFromFile( "./beeps.wav" ); checkError( "alutCreateBufferFromFile", ALUT ); alSourcef( src->source, AL_GAIN, 10.0f ); break; } case OBS: { alutGetError(); src->buffer = alutCreateBufferWaveform( ALUT_WAVEFORM_SQUARE, object_id_*100.0f + 100.0f, 0.0f, 0.7f ); checkError( "alutCreateBufferWaveform", ALUT ); alSourcef( src->source, AL_GAIN, 0.1f ); break; } default: break; } alSourcef( src->source, AL_PITCH, 1 ); alSource3f( src->source, AL_VELOCITY, 0.0f, 0.0f, 0.0f ); alSourcei( src->source, AL_LOOPING, AL_FALSE ); alSourcei( src->source, AL_BUFFER, src->buffer ); if ( regions_ ) { // move the location of the source in the OpenAL world to one of our discrete zones ALfloat pos[] = { 0.0, 0.0, 0.0 }; placeInRegion( x, z, pos ); alSourcefv( src->source, AL_POSITION, pos ); } else if ( cutoff_ ) { ALfloat pos[] = { 0.0, 0.0, 0.0 }; placeInCutoff( x, z, pos ); alSourcefv( src->source, AL_POSITION, pos ); } else { alSource3f( src->source, AL_POSITION, x, 0.0f, z ); } // insert the src into our map pthread_mutex_lock( &sources_lock_ ); sources_.insert( SoundMap::value_type( src->id, src ) ); pthread_mutex_unlock( &sources_lock_ ); // insert an entry for this source to our removed map pthread_mutex_lock( &remove_lock_ ); removed_.insert( BoolMap::value_type( src->id, false ) ); pthread_mutex_unlock( &remove_lock_ ); // insert an entry for this source to our paused map pthread_mutex_lock( &pause_lock_ ); paused_.insert( BoolMap::value_type( src->id, false ) ); pthread_mutex_unlock( &pause_lock_ ); // alSourcePlay( src->source ); // then insert it into the play queue pthread_mutex_lock( &q_lock_ ); play_q_.push( src ); pthread_mutex_unlock( &q_lock_ ); // alert the threads that a new object has been added pthread_cond_broadcast( &empty_q_lock_ ); // increment the id counter object_id_++; return src->id; }
void QALSource::setVelocity(float vx, float vy, float vz) { alSource3f(d->source, AL_VELOCITY, vx, vy, vz); }
void SonicDog::alertObstacles( const CoordinateVect &obstacles, bool diff ) { int size = obstacles.size(); // checkError( "alGenSources", AL ); pthread_mutex_lock( &q_lock_ ); if ( play_q_.size() > 0 ) { pthread_mutex_unlock( &q_lock_ ); return; } for ( int i = 0; i < size; i++ ) { SoundSrc *src = new SoundSrc; src->once = true; src->x = obstacles[i].first; src->z = obstacles[i].second; src->pause = 1.5; alGetError(); alGenSources( 1, &(src->source) ); checkError( "alGenSources", AL ); alutGetError(); if ( diff ) { // src->buffer = alutCreateBufferWaveform( ALUT_WAVEFORM_IMPULSE, i*100.0f+200.0f, 0.0f, 0.5f ); src->buffer = alutCreateBufferFromFile( "./ding.wav" ); alSourcef( src->source, AL_PITCH, .2*i+1 ); } else { // src->buffer = alutCreateBufferWaveform( ALUT_WAVEFORM_IMPULSE, 400.0f, 0.0f, 0.5f ); src->buffer = alutCreateBufferFromFile( "./ding.wav" ); alSourcef( src->source, AL_PITCH, 1 ); } if ( src->buffer == AL_NONE ) { checkError( "alutCreateBufferWaveform", ALUT ); } bool front = true; if ( regions_ ) { // move the location of the source in the OpenAL world to one of our discrete zones ALfloat pos[] = { 0.0, 0.0, 0.0 }; front = placeInRegion( src->x, src->z, pos ); alSourcefv( src->source, AL_POSITION, pos ); } else if ( cutoff_ ) { ALfloat pos[] = { 0.0, 0.0, 0.0 }; front = placeInCutoff( src->x, src->z, pos ); alSourcefv( src->source, AL_POSITION, pos ); } else { alSource3f( src->source, AL_POSITION, src->x, 0.0f, src->z ); } alSourcef( src->source, AL_GAIN, 10.0f ); alSource3f( src->source, AL_VELOCITY, 0.0f, 0.0f, 0.0f ); alSourcei( src->source, AL_LOOPING, AL_FALSE ); alSourcei( src->source, AL_BUFFER, src->buffer ); if ( front ) { play_q_.push( src ); } else if ( !front_only_ ) { play_q_.push( src ); } else { alDeleteSources( 1, &(src->source) ); alDeleteBuffers( 1, &(src->buffer) ); delete src; } } pthread_mutex_unlock( &q_lock_ ); pthread_cond_broadcast( &empty_q_lock_ ); }
Sound::SoundManager::SoundManager() : m_pDevice(alcOpenDevice(nullptr)) { if(!m_pDevice) LogError() << "Could not open audio device"; //m_Enumeration = alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"); ALCenum error; error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; m_pContext = alcCreateContext(m_pDevice, NULL); if (!alcMakeContextCurrent(m_pContext)) LogError() << "Could not make current context"; ALfloat listenerOri[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f }; alListener3f(AL_POSITION, 0, 0, 1.0f); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; alListener3f(AL_VELOCITY, 0, 0, 0); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; alListenerfv(AL_ORIENTATION, listenerOri); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; ALuint source; alGenSources((ALuint)1, &source); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; alSourcef(source, AL_PITCH, 1); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; alSourcef(source, AL_GAIN, 1); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; alSource3f(source, AL_POSITION, 0, 0, 0); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; alSource3f(source, AL_VELOCITY, 0, 0, 0); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; alSourcei(source, AL_LOOPING, AL_FALSE); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; ALuint buffer; alGenBuffers((ALuint)1, &buffer); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; ALsizei size, freq; ALenum format; ALvoid *data; ALboolean loop = AL_FALSE; alutLoadWAVFile(reinterpret_cast<ALbyte *>(const_cast<char *>("test.wav")), &format, &data, &size, &freq, &loop); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; alBufferData(buffer, format, data, size, freq); alSourcei(source, AL_BUFFER, buffer);alSourcePlay(source); alSourcePlay(source); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; ALint source_state; alGetSourcei(source, AL_SOURCE_STATE, &source_state); LogInfo() << "Play sound..."; while (source_state == AL_PLAYING) { alGetSourcei(source, AL_SOURCE_STATE, &source_state); error = alGetError(); if (error != AL_NO_ERROR) LogError() << error; LogInfo() << "Play sound..."; } // cleanup context alDeleteSources(1, &source); alDeleteBuffers(1, &buffer); m_pDevice = alcGetContextsDevice(m_pContext); alcMakeContextCurrent(NULL); alcDestroyContext(m_pContext); }
void LLAudioEngine_OpenAL::updateWind(LLVector3 wind_vec, F32 camera_altitude) { LLVector3 wind_pos; F64 pitch; F64 center_freq; ALenum error; if (!mEnableWind) return; if (!mWindBuf) return; if (mWindUpdateTimer.checkExpirationAndReset(LL_WIND_UPDATE_INTERVAL)) { // wind comes in as Linden coordinate (+X = forward, +Y = left, +Z = up) // need to convert this to the conventional orientation DS3D and OpenAL use // where +X = right, +Y = up, +Z = backwards wind_vec.setVec(-wind_vec.mV[1], wind_vec.mV[2], -wind_vec.mV[0]); pitch = 1.0 + mapWindVecToPitch(wind_vec); center_freq = 80.0 * pow(pitch,2.5*(mapWindVecToGain(wind_vec)+1.0)); mWindGen->mTargetFreq = (F32)center_freq; mWindGen->mTargetGain = (F32)mapWindVecToGain(wind_vec) * mMaxWindGain; mWindGen->mTargetPanGainR = (F32)mapWindVecToPan(wind_vec); alSourcei(mWindSource, AL_LOOPING, AL_FALSE); alSource3f(mWindSource, AL_POSITION, 0.0, 0.0, 0.0); alSource3f(mWindSource, AL_VELOCITY, 0.0, 0.0, 0.0); alSourcef(mWindSource, AL_ROLLOFF_FACTOR, 0.0); alSourcei(mWindSource, AL_SOURCE_RELATIVE, AL_TRUE); } // ok lets make a wind buffer now ALint processed, queued, unprocessed; alGetSourcei(mWindSource, AL_BUFFERS_PROCESSED, &processed); alGetSourcei(mWindSource, AL_BUFFERS_QUEUED, &queued); unprocessed = queued - processed; // ensure that there are always at least 3x as many filled buffers // queued as we managed to empty since last time. mNumEmptyWindALBuffers = llmin(mNumEmptyWindALBuffers + processed * 3 - unprocessed, MAX_NUM_WIND_BUFFERS-unprocessed); mNumEmptyWindALBuffers = llmax(mNumEmptyWindALBuffers, 0); //llinfos << "mNumEmptyWindALBuffers: " << mNumEmptyWindALBuffers <<" (" << unprocessed << ":" << processed << ")" << llendl; while (processed--) // unqueue old buffers { ALuint buffer; ALenum error; alGetError(); /* clear error */ alSourceUnqueueBuffers(mWindSource, 1, &buffer); error = alGetError(); if (error != AL_NO_ERROR) { llwarns << "LLAudioEngine_OpenAL::updateWind() error swapping (unqueuing) buffers" << llendl; } else { alDeleteBuffers(1, &buffer); } } unprocessed += mNumEmptyWindALBuffers; while (mNumEmptyWindALBuffers > 0) // fill+queue new buffers { ALuint buffer; alGetError(); /* clear error */ alGenBuffers(1,&buffer); if ((error=alGetError()) != AL_NO_ERROR) { llwarns << "LLAudioEngine_OpenAL::updateWind() Error creating wind buffer: " << convertALErrorToString(error) << llendl; break; } alBufferData(buffer, AL_FORMAT_STEREO16, mWindGen->windGenerate(mWindBuf, mWindBufSamples), mWindBufBytes, mWindBufFreq); error = alGetError(); if (error != AL_NO_ERROR) { llwarns << "LLAudioEngine_OpenAL::updateWind() error swapping (bufferdata) buffers" << llendl; } alSourceQueueBuffers(mWindSource, 1, &buffer); error = alGetError(); if (error != AL_NO_ERROR) { llwarns << "LLAudioEngine_OpenAL::updateWind() error swapping (queuing) buffers" << llendl; } --mNumEmptyWindALBuffers; } ALint playing; alGetSourcei(mWindSource, AL_SOURCE_STATE, &playing); if (playing != AL_PLAYING) { alSourcePlay(mWindSource); lldebugs << "Wind had stopped - probably ran out of buffers - restarting: " << (unprocessed+mNumEmptyWindALBuffers) << " now queued." << llendl; } }
void AudioWorld::initializeMusic() { std::string datPath = "/_work/data/Scripts/_compiled/MUSIC.DAT"; std::string datFile = Utils::getCaseSensitivePath(datPath, m_Engine.getEngineArgs().gameBaseDirectory); if (!Utils::fileExists(datFile)) { LogError() << "Failed to find MUSIC.DAT at: " << datFile; return; } m_MusicVM = new Daedalus::DaedalusVM(datFile); Daedalus::registerGothicEngineClasses(*m_MusicVM); m_MusicVM->getDATFile().iterateSymbolsOfClass("C_MUSICTHEME", [&](size_t i, Daedalus::PARSymbol& s) { Daedalus::GameState::MusicThemeHandle h = m_MusicVM->getGameState().createMusicTheme(); Daedalus::GEngineClasses::C_MusicTheme& mt = m_MusicVM->getGameState().getMusicTheme(h); m_MusicVM->initializeInstance(ZMemory::toBigHandle(h), i, Daedalus::IC_MusicTheme); m_musicThemeSegments[s.name] = mt.file; }); // DirectMusic initialization std::string baseDir = m_Engine.getEngineArgs().gameBaseDirectory; std::string musicPath = Utils::getCaseSensitivePath("/_work/data/Music", baseDir); try { const auto sfFactory = DirectMusic::DlsPlayer::createFactory(); m_musicContext = std::make_unique<DirectMusic::PlayingContext>(44100, 2, sfFactory); auto loader = [musicPath, baseDir](const std::string& name) { const auto search = Utils::lowered(Utils::stripFilePath(name)); for (const auto& file : Utils::getFilesInDirectory(musicPath)) { const auto lowercaseName = Utils::lowered(Utils::stripFilePath(file)); if (lowercaseName == search) { return Utils::readBinaryFileContents(file); } } return std::vector<std::uint8_t>(); }; m_musicContext->provideLoader(loader); for (const auto& segment : Utils::getFilesInDirectory(musicPath, "sgt")) { const auto lowercaseName = Utils::lowered(Utils::stripFilePath(segment)); const auto segm = m_musicContext->loadSegment(segment); LogInfo() << "Loading " + segment; m_Segments[lowercaseName] = m_musicContext->prepareSegment(*segm); } LogInfo() << "All segments loaded."; alGenBuffers(RE_NUM_MUSIC_BUFFERS, m_musicBuffers); alGenSources(1, &m_musicSource); // Set the default volume alSourcef(m_musicSource, AL_GAIN, 1); // Set the default position of the sound alSource3f(m_musicSource, AL_POSITION, 0, 0, 0); m_musicRenderThread = std::thread(&AudioWorld::musicRenderFunction, this); } catch (const std::exception& exc) { LogError() << "Couldn't initialize music system: " << exc.what(); } }
int main(int argc, char **argv) { ALboolean enumeration; const ALCchar *devices; const ALCchar *defaultDeviceName = argv[1]; int ret; #ifdef LIBAUDIO WaveInfo *wave; #endif char *bufferData; ALCdevice *device; ALvoid *data; ALCcontext *context; ALsizei size, freq; ALenum format; ALuint buffer, source; ALfloat listenerOri[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f }; ALboolean loop = AL_FALSE; ALCenum error; ALint source_state; enumeration = alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"); if (enumeration == AL_FALSE) fprintf(stderr, "enumeration extension not available\n"); list_audio_devices(alcGetString(NULL, ALC_DEVICE_SPECIFIER)); if (!defaultDeviceName) defaultDeviceName = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER); device = alcOpenDevice(defaultDeviceName); if (!device) { fprintf(stderr, "unable to open default device\n"); return -1; } fprintf(stdout, "Device: %s\n", alcGetString(device, ALC_DEVICE_SPECIFIER)); alGetError(); context = alcCreateContext(device, NULL); if (!alcMakeContextCurrent(context)) { fprintf(stderr, "failed to make default context\n"); return -1; } TEST_ERROR("make default context"); /* set orientation */ alListener3f(AL_POSITION, 0, 0, 1.0f); TEST_ERROR("listener position"); alListener3f(AL_VELOCITY, 0, 0, 0); TEST_ERROR("listener velocity"); alListenerfv(AL_ORIENTATION, listenerOri); TEST_ERROR("listener orientation"); alGenSources((ALuint)1, &source); TEST_ERROR("source generation"); alSourcef(source, AL_PITCH, 1); TEST_ERROR("source pitch"); alSourcef(source, AL_GAIN, 1); TEST_ERROR("source gain"); alSource3f(source, AL_POSITION, 0, 0, 0); TEST_ERROR("source position"); alSource3f(source, AL_VELOCITY, 0, 0, 0); TEST_ERROR("source velocity"); alSourcei(source, AL_LOOPING, AL_FALSE); TEST_ERROR("source looping"); alGenBuffers(1, &buffer); TEST_ERROR("buffer generation"); #ifdef LIBAUDIO /* load data */ wave = WaveOpenFileForReading("test.wav"); if (!wave) { fprintf(stderr, "failed to read wave file\n"); return -1; } ret = WaveSeekFile(0, wave); if (ret) { fprintf(stderr, "failed to seek wave file\n"); return -1; } bufferData = malloc(wave->dataSize); if (!bufferData) { perror("malloc"); return -1; } ret = WaveReadFile(bufferData, wave->dataSize, wave); if (ret != wave->dataSize) { fprintf(stderr, "short read: %d, want: %d\n", ret, wave->dataSize); return -1; } alBufferData(buffer, to_al_format(wave->channels, wave->bitsPerSample), bufferData, wave->dataSize, wave->sampleRate); TEST_ERROR("failed to load buffer data"); #else alutLoadWAVFile("test.wav", &format, &data, &size, &freq, &loop); TEST_ERROR("loading wav file"); alBufferData(buffer, format, data, size, freq); TEST_ERROR("buffer copy"); #endif alSourcei(source, AL_BUFFER, buffer); TEST_ERROR("buffer binding"); alSourcePlay(source); TEST_ERROR("source playing"); alGetSourcei(source, AL_SOURCE_STATE, &source_state); TEST_ERROR("source state get"); while (source_state == AL_PLAYING) { alGetSourcei(source, AL_SOURCE_STATE, &source_state); TEST_ERROR("source state get"); } /* exit context */ alDeleteSources(1, &source); alDeleteBuffers(1, &buffer); device = alcGetContextsDevice(context); alcMakeContextCurrent(NULL); alcDestroyContext(context); alcCloseDevice(device); return 0; }