COALDevice::COALDevice(CRefPtr<COALAdapter> pAdapter) : Manage::IManagedObject<COALAdapter, COALDevice>(pAdapter), m_pContext(0) { Log::Write(L"Initializing OpenAL Device..."); ALCint attibs[] = { ALC_MAJOR_VERSION, 1, ALC_MINOR_VERSION, 1, 0, 0, }; this->m_pContext = alcCreateContext(this->m_pParent->GetALCDevice(), attibs); if(!this->m_pContext){ auto uError = alcGetError(this->m_pParent->GetALCDevice()); CR_THROW(L"Failed to create device for adapter " + this->m_pParent->GetName() + L", error: " + String::ToHexString(uError)); } if(!alcMakeContextCurrent(this->m_pContext)){ auto uError = alcGetError(this->m_pParent->GetALCDevice()); alcDestroyContext(this->m_pContext); CR_THROW(L"Failed to make context current for adapter " + this->m_pParent->GetName() + L", error: " + String::ToHexString(uError)); } //AL::LoadExtensions(this->m_pParent->GetALCDevice()); }
bool Manager_Impl_OpenAL::InitializeInternal() { m_device = alcOpenDevice(NULL); if (!m_device) return false; m_context = alcCreateContext(m_device, NULL); if (!m_context) return false; alcMakeContextCurrent(m_context); alGenSources(1, &m_source); if (!m_source) return false; m_buffers.resize(queueSize); alGenBuffers(queueSize, &m_buffers[0]); alSourcei(m_source, AL_LOOPING, AL_FALSE); m_threading = true; m_thread = std::thread(ThreadFunc, this); return true; }
SoundManager::SoundManager() { ALCdevice *device; device = alcOpenDevice(NULL); if (!device) { //printf("ERROR DEVICE OPENAL !!"); } ALCcontext *context; context = alcCreateContext(device, NULL); if (!alcMakeContextCurrent(context)) { //printf("ERROR CONTEXT OPENAL !!"); } //ALboolean enumeration; //std::cout << alGetString(AL_VERSION) << std::endl; //std::cout << alGetString(AL_RENDERER) << std::endl; }
int main(int argc, char *argv[]){ const int bufsize = BUFSIZE; ALCdevice* device = alcOpenDevice(NULL); alcGetError(device); ALCcontext* context = alcCreateContext(device, NULL); alcMakeContextCurrent(context); ALshort data[SSIZE]; ALuint buffer[BUFSIZE]; ALuint playsource; alGenBuffers(BUFSIZE, buffer); pthread_t playThread, queueingThread; pthread_attr_t playThread_attr, queueingThread_attr; alGenSources(1, &playsource); pthread_attr_init(&playThread_attr); pthread_attr_setdetachstate(&playThread_attr , PTHREAD_CREATE_DETACHED); if(pthread_create(&playThread , &playThread_attr , playFunc , NULL) !=0) perror("pthread_create()"); pthread_attr_destroy(&playThread_attr); }
//////////////////////////////////////////////////////////// /// Default constructor //////////////////////////////////////////////////////////// AudioDevice::AudioDevice() : myRefCount(0) { float listenerDepth = 0.1; // Create the device myDevice = alcOpenDevice(NULL); PrintOpenALInfo(); if (myDevice) { // Create the context myContext = alcCreateContext(myDevice, NULL); if (myContext) { // Set the context as the current one (we'll only need one) alcMakeContextCurrent(myContext); // Initialize the listener, located at the origin and looking along the Z axis Listener::SetPosition(0,0,listenerDepth); Listener::SetTarget(0,0,-listenerDepth); //preloadSources(); //exit(1); } else { std::cerr << "Failed to create the audio context" << std::endl; } } else { std::cerr << "Failed to open the audio device" << std::endl; } }
OpenALManager::OpenALManager() { ALCdevice *device; device = alcOpenDevice(NULL); CHECK_AL_ERROR; if (!device) throw std::runtime_error("Can't create a device "); CHECK_ALC_ERROR(device); auto context = alcCreateContext(device, NULL); CHECK_ALC_ERROR(device); CHECK_AL_ERROR; auto success = alcMakeContextCurrent(context); CHECK_ALC_ERROR(device); CHECK_AL_ERROR; if (!success) throw std::runtime_error("Can't select a context"); alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f); CHECK_ALC_ERROR(device); CHECK_AL_ERROR; }
void Sound::initSound() { if (world->nosound) { return; } if (world->assetsDir.empty()) { return; } setDir(world->assetsDir+"/sounds/"); // Open device, create context ALCdevice *Device = alcOpenDevice(NULL); ALCcontext *Context; Context = alcCreateContext(Device, NULL); alcMakeContextCurrent(Context); // Load sound files into sound library vector<string> *wav_filenames = get_wav_filenames(); if (!wav_filenames) return; for (vector<string>::iterator it = wav_filenames->begin(); it != wav_filenames->end(); it++) { ALuint buf = filenameToBuffer(base_sound_directory + *it); sound_resource *a = new sound_resource(buf); sound_library.insert(std::pair<const string, sound_resource*>(*it, a)); error->log(SOUND, TRIVIAL, "loaded sound from " + *it + " into buffer #" + boost::lexical_cast<string>(buf) + "\n"); } delete wav_filenames; initialized = true; return; }
Mixer::Mixer () { const ALCchar * device_name = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER); AudioError::reset(); _audio_device = _default_audio_device(); _audio_context = alcCreateContext(_audio_device, NULL); AudioError::check("Initializing Audio Context"); bool result = alcMakeContextCurrent(_audio_context); LogBuffer buffer; buffer << "OpenAL Context Initialized..." << std::endl; buffer << "OpenAL Vendor: " << alGetString(AL_VENDOR) << " " << alGetString(AL_VERSION) << std::endl; buffer << "OpenAL Device: '" << device_name << "'" << std::endl; logger()->log(LOG_INFO, buffer); //al_distance_model(AL_LINEAR_DISTANCE); set_listener_position(0); set_listener_velocity(0); set_listener_orientation(Vec3(0.0, 0.0, -1.0), Vec3(0.0, 1.0, 0.0)); DREAM_ASSERT(result && "Failed to initialize audio hardware!?"); }
SoundSystem::SoundSystem(int32 _maxChannels) : maxChannels(_maxChannels), volume(1.f) { #ifdef __DAVASOUND_AL__ device = alcOpenDevice(0); if(device) { context = alcCreateContext(device, 0); AL_CHECKERROR(); AL_VERIFY(alcMakeContextCurrent(context)); } #endif for(int32 i = 0; i < maxChannels; ++i) { SoundChannel * ch = new SoundChannel(); channelsPool.push_back(ch); } groupFX = new SoundGroup(); groupMusic = new SoundGroup(); }
void SoundPool::init_openal() { printf("initialising OpenAL\n"); device = alcOpenDevice(NULL); context = alcCreateContext(device, NULL); alcMakeContextCurrent(context); ALfloat orientation[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f }; alListener3f(AL_POSITION, 0, 0, 1.0f); alListener3f(AL_VELOCITY, 0, 0, 0); alListenerfv(AL_ORIENTATION, orientation); for (auto &source : sounds_) { alGenSources(1, &source); alSourcef(source, AL_GAIN, 1.0f); alSourcef(source, AL_PITCH, 1.0f); alSource3f(source, AL_POSITION, 0, 0, 0); alSource3f(source, AL_VELOCITY, 0, 0, 0); alSourcei(source, AL_LOOPING, AL_FALSE); } openal_initialised = true; }
AudioDevice::AudioDevice() { m_Device = alcOpenDevice(NULL); if (!m_Device) { std::cout << "Failed to initialize OpenAL!" << std::endl; return; } m_Context = alcCreateContext(m_Device, NULL); if (!m_Context) { std::cout << "Failed to initialize OpenAL!" << std::endl; return; } alcMakeContextCurrent(m_Context); unsigned int* ids = new unsigned int[AUDIO_SOURCE_MAX]; alGenSources(AUDIO_SOURCE_MAX, ids); for (int i = 0; i < AUDIO_SOURCE_MAX; i++) { m_Sources[i] = new AudioSource(this, ids[i]); } delete ids; }
AudioDevice::AudioDevice() { // Create the device audioDevice = alcOpenDevice(NULL); if (audioDevice) { // Create the context audioContext = alcCreateContext(audioDevice, NULL); if (audioContext) { // Set the context as the current one (we'll only need one) alcMakeContextCurrent(audioContext); // Apply the listener properties the user might have set float orientation[] = {listenerDirection.x, listenerDirection.y, listenerDirection.z, listenerUpVector.x, listenerUpVector.y, listenerUpVector.z}; alCheck(alListenerf(AL_GAIN, listenerVolume * 0.01f)); alCheck(alListener3f(AL_POSITION, listenerPosition.x, listenerPosition.y, listenerPosition.z)); alCheck(alListenerfv(AL_ORIENTATION, orientation)); } else { err() << "Failed to create the audio context" << std::endl; } } else { err() << "Failed to open the audio device" << std::endl; } }
void cSoundMgr::createContext() { m_OALDevice = alcOpenDevice(NULL); // Check for if (!m_OALDevice) { OutputDebugString("Cannot create audio ALCdevice"); return; } else { //Create a context m_OALContext = alcCreateContext(m_OALDevice, NULL); //Set active context alcMakeContextCurrent(m_OALContext); if (!m_OALContext) { OutputDebugString("Cannot create audio ALCcontext"); return; } } }
AudioPlayer::AudioPlayer(const char *_waveFile, const int FFTwindowSize) { waveFile = _waveFile; // Create a audio context device = alcOpenDevice(NULL); context = alcCreateContext(device, NULL); alcMakeContextCurrent(context); // Create a audio listener alListener3f(AL_POSITION, 0, 0, 0); alListener3f(AL_VELOCITY, 0, 0, 0); alListener3f(AL_ORIENTATION, 0, 0, -1); // Create a audio source alGenSources(1, &source); // Setup properties of audio source alSourcef(source, AL_PITCH, 1); alSourcef(source, AL_GAIN, 1); alSource3f(source, AL_POSITION, 0, 0, 0); alSource3f(source, AL_VELOCITY, 0, 0, 0); alSourcei(source, AL_LOOPING, AL_FALSE); // Create a audio buffer alGenBuffers(1, &buffer); // No WAVE file is loaded isLoaded = false; // Setup FFTW N = FFTwindowSize; fftIn = new double[N]; fftOut = new fftw_complex[ getNumberFrequencies() ]; fftPlan = fftw_plan_dft_r2c_1d(N, fftIn, fftOut, FFTW_ESTIMATE); loadWave(); }
int init(void){ device = alcOpenDevice(NULL); if(device) { context = alcCreateContext(device, NULL); } alcMakeContextCurrent(context); if (enet_initialize () != 0) { fprintf (stderr, "An error occurred while initializing ENet.\n"); return EXIT_FAILURE; } atexit (enet_deinitialize); atexit (alCleanUp); atexit (clean_up); enet_client = enet_host_create (NULL /* create a client host */, 1 /* only allow 1 outgoing connection */, 0 /* allow up 4 channels to be used, 0 and 1 */, 0 /* 56K modem with 56 Kbps downstream bandwidth */, 0 /* 56K modem with 14 Kbps upstream bandwidth */); if (enet_client == NULL) { fprintf (stderr, "An error occurred while trying to create an ENet client host.\n"); exit (EXIT_FAILURE); } tclient = client_init(enet_client); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_POINT_SMOOTH); glEnable(GL_LINE_SMOOTH); }
OpenALSoundSystem::OpenALSoundSystem() { m_device = alcOpenDevice ( NULL ); ARCReleaseAssert ( m_device != NULL ); m_context = alcCreateContext ( m_device, arc_openal_attributes ); alcProcessContext ( m_context ); alcMakeContextCurrent ( m_context ); for (unsigned int i = 0; i < arc_openal_num_sources; i++) { ALuint source; alGenSources ( 1, &source ); m_freeSources.insert(source); } for ( size_t i = 0; i < m_queues.size(); i++ ) { if ( !m_queues.valid ( i ) ) continue; delete m_queues.get ( i ); m_queues.remove ( i ); } alDistanceModel ( AL_INVERSE_DISTANCE_CLAMPED ); }
internal bool32 initialize_sound(sound_array *sounds) { ALCdevice *device = g_audioDevice = alcOpenDevice(NULL); if (device) { g_audioContext = alcCreateContext(device, NULL); if (alcMakeContextCurrent(g_audioContext)) { if (!start_new_log(AL_LOG_FILE)) { fprintf(stderr, "Failed to create new log file: %s\n", AL_LOG_FILE); } alListenerfv(AL_POSITION, g_listenerPos); alListenerfv(AL_VELOCITY, g_listenerVel); alListenerfv(AL_ORIENTATION, g_listenerOri); if (al_print_if_error("Failed to initialize listener\n")) return false; alGenSources(sounds->size, sounds->sources); if (al_print_if_error("Failed to generate audio sources\n")) return false; } else { al_log(true, "OpenAL: failed to make audio context current\n"); return false; } } else { al_log(true, "Failed to open device\n"); // TODO: fix bug where alcOpenDevice occasionally fails return false; } return true; }
void Audio::openOutput(const QString& outDevDescr) { auto* tmp = alOutDev; alOutDev = nullptr; if (outDevDescr.isEmpty()) alOutDev = alcOpenDevice(nullptr); else alOutDev = alcOpenDevice(outDevDescr.toStdString().c_str()); if (!alOutDev) { qWarning() << "Audio: Cannot open output audio device"; } else { if (alContext) { alcMakeContextCurrent(nullptr); alcDestroyContext(alContext); } if (tmp) alcCloseDevice(tmp); alContext=alcCreateContext(alOutDev,nullptr); if (!alcMakeContextCurrent(alContext)) { qWarning() << "Audio: Cannot create output audio context"; alcCloseDevice(alOutDev); } else alGenSources(1, &alMainSource); qDebug() << "Audio: Opening audio output "<<outDevDescr; } Core::getInstance()->resetCallSources(); // Force to regen each group call's sources }
int init() { LOG("\n============================================"); LOG_DEBUG("init()"); if (device && context) { LOG("Already initialized"); return SUCCESS; } device = alcOpenDevice(NULL); if (!device) { EXCEPTION("Failed to open OpenAL Device"); } context = alcCreateContext(device, context_attribs); if (!context) { EXCEPTION("Failed to create OpenAL Context"); } alcMakeContextCurrent(context); LOG("Device and context successfully initialized"); return SUCCESS; }
int main( int argc, char* argv[] ) { ALCdevice *dev; int attrlist[] = { ALC_FREQUENCY, 22050, 0 }; time_t shouldend, start; ALint test = AL_FALSE; dev = alcOpenDevice( NULL ); if( dev == NULL ) { return 1; } /* Initialize ALUT. */ context_id = alcCreateContext( dev, attrlist); if(context_id == NULL) { alcCloseDevice( dev ); exit(1); } alcMakeContextCurrent( context_id ); fixup_function_pointers(); talBombOnError(); if(argc == 1) { init(WAVEFILE); } else { init(argv[1]); } fprintf( stderr, "Loop for 4 seconds\n"); alSourcePlay( moving_source ); shouldend = start = time( NULL ); while( shouldend - start <= 4 ) { shouldend = time(NULL); micro_sleep( 1000000 ); } alSourceStop( moving_source ); test = -1; alGetSourceiv( moving_source, AL_LOOPING, &test ); fprintf(stderr, "is looping? getsi says %s\n", (test == AL_TRUE)?"AL_TRUE":"AL_FALSE"); /* part the second */ fprintf( stderr, "Play once\n"); micro_sleep( 1000000 ); alSourcei( moving_source, AL_LOOPING, AL_FALSE ); alSourcePlay( moving_source ); do { micro_sleep( 1000000 ); } while( SourceIsPlaying( moving_source ) ); alcDestroyContext(context_id); alcCloseDevice( dev ); cleanup(); return 0; }
ALCcontext* dll_alc_CreateContext(ALCdevice *device, const ALCint* attrlist) { return alcCreateContext(device, attrlist); }
/// Initialize OpenAl and return true on success. // TODO rewrite with std::unique_ptr and custom deleter to remove long // chain of "destructor" code. void Sound::Impl::InitOpenAL() { ALCcontext *context; ALCdevice *device; ALenum error_code; ALboolean status; device = alcOpenDevice(nullptr); if (!device) { ErrorLogger() << "Unable to initialise default OpenAL device."; m_initialized = false; return; } context = alcCreateContext(device, nullptr); if (!context) { error_code = alGetError(); ErrorLogger() << "Unable to create OpenAL context: " << alGetString(error_code) << "\n"; alcCloseDevice(device); m_initialized = false; return; } status = alcMakeContextCurrent(context); error_code = alGetError(); if (status != AL_TRUE || error_code != AL_NO_ERROR) { ErrorLogger() << "Unable to make OpenAL context current: " << alGetString(error_code) << "\n"; alcDestroyContext(context); alcCloseDevice(device); m_initialized = false; return; } alListenerf(AL_GAIN, 1.0); error_code = alGetError(); if (error_code != AL_NO_ERROR) { ErrorLogger() << "Unable to create OpenAL listener: " << alGetString(error_code) << "\n" << "Disabling OpenAL sound system!\n"; alcMakeContextCurrent(nullptr); alcDestroyContext(context); alcCloseDevice(device); m_initialized = false; return; } alGenSources(NUM_SOURCES, m_sources); error_code = alGetError(); if (error_code != AL_NO_ERROR) { ErrorLogger() << "Unable to create OpenAL sources: " << alGetString(error_code) << "\n" << "Disabling OpenAL sound system!\n"; alcMakeContextCurrent(nullptr); alcDestroyContext(context); alcCloseDevice(device); m_initialized = false; return; } alGenBuffers(NUM_MUSIC_BUFFERS, m_music_buffers); error_code = alGetError(); if (error_code != AL_NO_ERROR) { ErrorLogger() << "Unable to create OpenAL buffers: " << alGetString(error_code) << "\n" << "Disabling OpenAL sound system!\n"; alDeleteSources(NUM_SOURCES, m_sources); alcMakeContextCurrent(nullptr); alcDestroyContext(context); alcCloseDevice(device); m_initialized = false; return; } for (int i = 0; i < NUM_SOURCES; ++i) { alSourcei(m_sources[i], AL_SOURCE_RELATIVE, AL_TRUE); error_code = alGetError(); if (error_code != AL_NO_ERROR) { ErrorLogger() << "Unable to set OpenAL source to relative: " << alGetString(error_code) << "\n" << "Disabling OpenAL sound system!\n"; alDeleteBuffers(NUM_MUSIC_BUFFERS, m_music_buffers); alDeleteSources(NUM_SOURCES, m_sources); alcMakeContextCurrent(nullptr); alcDestroyContext(context); alcCloseDevice(device); m_initialized = false; return; } } DebugLogger() << "OpenAL initialized. Version " << alGetString(AL_VERSION) << " Renderer " << alGetString(AL_RENDERER) << " Vendor " << alGetString(AL_VENDOR) << "\n" << " Extensions: " << alGetString(AL_EXTENSIONS) << "\n"; m_initialized = true; }
/** * Initializes the audio device and creates sources. * * @warning: * * @return TRUE if initialization was successful, FALSE otherwise */ bool FALAudioDevice::InitializeHardware( void ) { // Make sure no interface classes contain any garbage Effects = NULL; DLLHandle = NULL; // Default to sensible channel count. if( MaxChannels < 1 ) { MaxChannels = 32; } // Load ogg and vorbis dlls if they haven't been loaded yet //LoadVorbisLibraries(); // Open device HardwareDevice = alcOpenDevice(nullptr); if( !HardwareDevice ) { UE_LOG(LogALAudio, Log, TEXT( "ALAudio: no OpenAL devices found." ) ); return false ; } // Display the audio device that was actually opened const ALCchar* OpenedDeviceName = alcGetString( HardwareDevice, ALC_DEVICE_SPECIFIER ); UE_LOG(LogALAudio, Log, TEXT("ALAudio device opened : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(OpenedDeviceName)).Get()); // Create a context int Caps[] = { ALC_FREQUENCY, 44100, ALC_STEREO_SOURCES, 4, 0, 0 }; #if PLATFORM_HTML5_WIN32 || PLATFORM_LINUX SoundContext = alcCreateContext( HardwareDevice, Caps ); #elif PLATFORM_HTML5 SoundContext = alcCreateContext( HardwareDevice, 0 ); #endif if( !SoundContext ) { return false ; } alcMakeContextCurrent(SoundContext); // Make sure everything happened correctly if( alError( TEXT( "Init" ) ) ) { UE_LOG(LogALAudio, Warning, TEXT("ALAudio: alcMakeContextCurrent failed.")); return false ; } UE_LOG(LogALAudio, Log, TEXT("AL_VENDOR : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(alGetString(AL_VENDOR))).Get()); UE_LOG(LogALAudio, Log, TEXT("AL_RENDERER : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(alGetString(AL_RENDERER))).Get()); UE_LOG(LogALAudio, Log, TEXT("AL_VERSION : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(alGetString(AL_VERSION))).Get()); UE_LOG(LogALAudio, Log, TEXT("AL_EXTENSIONS : %s"), StringCast<TCHAR>(static_cast<const ANSICHAR*>(alGetString(AL_EXTENSIONS))).Get()); // Get the enums for multichannel support #if !PLATFORM_HTML5 Surround40Format = alGetEnumValue( "AL_FORMAT_QUAD16" ); Surround51Format = alGetEnumValue( "AL_FORMAT_51CHN16" ); Surround61Format = alGetEnumValue( "AL_FORMAT_61CHN16" ); Surround71Format = alGetEnumValue( "AL_FORMAT_71CHN16" ); #endif // Initialize channels. alError( TEXT( "Emptying error stack" ), 0 ); for( int i = 0; i < (( MaxChannels > MAX_AUDIOCHANNELS ) ? MAX_AUDIOCHANNELS : MaxChannels); i++ ) { ALuint SourceId; alGenSources( 1, &SourceId ); if( !alError( TEXT( "Init (creating sources)" ), 0 ) ) { FALSoundSource* Source = new FALSoundSource( this ); Source->SourceId = SourceId; Sources.Add( Source ); FreeSources.Add( Source ); } else { break; } } if( Sources.Num() < 1 ) { UE_LOG(LogALAudio, Warning, TEXT("ALAudio: couldn't allocate any sources")); return false ; } // Update MaxChannels in case we couldn't create enough sources. MaxChannels = Sources.Num(); UE_LOG(LogALAudio, Verbose, TEXT("ALAudioDevice: Allocated %i sources"), MaxChannels); // Use our own distance model. alDistanceModel( AL_NONE ); // Set up a default (nop) effects manager Effects = new FAudioEffectsManager( this ); return true ; }
Sound_Renderer_AL::Sound_Renderer_AL() : m_device(0), m_context(0), m_bgm(0), m_bgm_source(0) { #ifndef _MACOSX #ifdef _WINDOWS m_openal32 = LoadLibrary("OpenAL32.dll"); #else m_openal32 = LoadLibrary("libopenal.so"); #endif if(!m_openal32) { std::cerr << "Loading OpenAL32.dll failed." << std::endl; throw Sound_Init_Failure(); } g_alBufferData = (alBufferData_fcn)GetProcAddress(m_openal32, "alBufferData"); g_alcCloseDevice = (alcCloseDevice_fcn)GetProcAddress(m_openal32, "alcCloseDevice"); g_alcCreateContext = (alcCreateContext_fcn)GetProcAddress(m_openal32, "alcCreateContext"); g_alcDestroyContext = (alcDestroyContext_fcn)GetProcAddress(m_openal32, "alcDestroyContext"); g_alIsExtensionPresent = (alIsExtensionPresent_fcn)GetProcAddress(m_openal32, "alIsExtensionPresent"); g_alcMakeContextCurrent = (alcMakeContextCurrent_fcn)GetProcAddress(m_openal32, "alcMakeContextCurrent"); g_alcOpenDevice = (alcOpenDevice_fcn)GetProcAddress(m_openal32, "alcOpenDevice"); g_alDeleteBuffers = (alDeleteBuffers_fcn)GetProcAddress(m_openal32, "alDeleteBuffers"); g_alDeleteSources = (alDeleteSources_fcn)GetProcAddress(m_openal32, "alDeleteSources"); g_alGenBuffers = (alGenBuffers_fcn)GetProcAddress(m_openal32, "alGenBuffers"); g_alGetError = (alGetError_fcn)GetProcAddress(m_openal32, "alGetError"); g_alGetListenerf = (alGetListenerf_fcn)GetProcAddress(m_openal32, "alGetListenerf"); g_alGetListenerfv = (alGetListenerfv_fcn)GetProcAddress(m_openal32, "alGetListenerfv"); g_alGetSourcef = (alGetSourcef_fcn)GetProcAddress(m_openal32, "alGetSourcef"); g_alGetSourcefv = (alGetSourcefv_fcn)GetProcAddress(m_openal32, "alGetSourcefv"); g_alGetSourcei = (alGetSourcei_fcn)GetProcAddress(m_openal32, "alGetSourcei"); g_alGenSources = (alGenSources_fcn)GetProcAddress(m_openal32, "alGenSources"); g_alListenerf = (alListenerf_fcn)GetProcAddress(m_openal32, "alListenerf"); g_alListenerfv = (alListenerfv_fcn)GetProcAddress(m_openal32, "alListenerfv"); g_alSourcef = (alSourcef_fcn)GetProcAddress(m_openal32, "alSourcef"); g_alSourcefv = (alSourcefv_fcn)GetProcAddress(m_openal32, "alSourcefv"); g_alSourcei = (alSourcei_fcn)GetProcAddress(m_openal32, "alSourcei"); g_alSourcePause = (alSourcePause_fcn)GetProcAddress(m_openal32, "alSourcePause"); g_alSourcePlay = (alSourcePlay_fcn)GetProcAddress(m_openal32, "alSourcePlay"); g_alSourceStop = (alSourceStop_fcn)GetProcAddress(m_openal32, "alSourceStop"); if(!g_alBufferData || !g_alcCloseDevice || !g_alcCreateContext || !g_alcDestroyContext || !g_alIsExtensionPresent || !g_alcMakeContextCurrent || !g_alcOpenDevice || !g_alDeleteBuffers || !g_alDeleteSources || !g_alGenBuffers || !g_alGetError || !g_alGetListenerf || !g_alGetListenerfv || !g_alGetSourcef || !g_alGetSourcefv || !g_alGetSourcei || !g_alGenSources || !g_alListenerf || !g_alListenerfv || !g_alSourcef || !g_alSourcefv || !g_alSourcei || !g_alSourcePause || !g_alSourcePlay || !g_alSourceStop) { std::cerr << "Loading OpenAL32.dll failed." << std::endl; zero_handles(); FreeLibrary(m_openal32); throw Sound_Init_Failure(); } #ifdef _WINDOWS m_libvorbisfile = LoadLibrary("libvorbisfile.dll"); #else m_libvorbisfile = LoadLibrary("libvorbisfile.so"); #endif if(!m_libvorbisfile) { std::cerr << "Loading libvorbisfile.dll failed." << std::endl; zero_handles(); FreeLibrary(m_openal32); throw Sound_Init_Failure(); } g_ov_clear = (ov_clear_fcn)GetProcAddress(m_libvorbisfile, "ov_clear"); g_ov_info = (ov_info_fcn)GetProcAddress(m_libvorbisfile, "ov_info"); g_ov_fopen = (ov_fopen_fcn)GetProcAddress(m_libvorbisfile, "ov_fopen"); g_ov_pcm_total = (ov_pcm_total_fcn)GetProcAddress(m_libvorbisfile, "ov_pcm_total"); g_ov_read = (ov_read_fcn)GetProcAddress(m_libvorbisfile, "ov_read"); if(!g_ov_clear || !g_ov_info || !g_ov_fopen || !g_ov_pcm_total || !g_ov_read) { std::cerr << "Loading libvorbisfile.dll failed." << std::endl; zero_handles(); FreeLibrary(m_libvorbisfile); FreeLibrary(m_openal32); throw Sound_Init_Failure(); } #else g_alBufferData = (alBufferData_fcn)::alBufferData; g_alcCloseDevice = (alcCloseDevice_fcn)::alcCloseDevice; g_alcCreateContext = (alcCreateContext_fcn)::alcCreateContext; g_alcDestroyContext = (alcDestroyContext_fcn)::alcDestroyContext; g_alIsExtensionPresent = (alIsExtensionPresent_fcn)::alIsExtensionPresent; g_alcMakeContextCurrent = (alcMakeContextCurrent_fcn)::alcMakeContextCurrent; g_alcOpenDevice = (alcOpenDevice_fcn)::alcOpenDevice; g_alDeleteBuffers = (alDeleteBuffers_fcn)::alDeleteBuffers; g_alDeleteSources = (alDeleteSources_fcn)::alDeleteSources; g_alGenBuffers = (alGenBuffers_fcn)::alGenBuffers; g_alGetError = (alGetError_fcn)::alGetError; g_alGetListenerf = (alGetListenerf_fcn)::alGetListenerf; g_alGetListenerfv = (alGetListenerfv_fcn)::alGetListenerfv; g_alGetSourcef = (alGetSourcef_fcn)::alGetSourcef; g_alGetSourcefv = (alGetSourcefv_fcn)::alGetSourcefv; g_alGetSourcei = (alGetSourcei_fcn)::alGetSourcei; g_alGenSources = (alGenSources_fcn)::alGenSources; g_alListenerf = (alListenerf_fcn)::alListenerf; g_alListenerfv = (alListenerfv_fcn)::alListenerfv; g_alSourcef = (alSourcef_fcn)::alSourcef; g_alSourcefv = (alSourcefv_fcn)::alSourcefv; g_alSourcei = (alSourcei_fcn)::alSourcei; g_alSourcePause = (alSourcePause_fcn)::alSourcePause; g_alSourcePlay = (alSourcePlay_fcn)::alSourcePlay; g_alSourceStop = (alSourceStop_fcn)::alSourceStop; g_ov_clear = (ov_clear_fcn)::ov_clear; g_ov_info = (ov_info_fcn)::ov_info; g_ov_fopen = (ov_fopen_fcn)::ov_fopen; g_ov_pcm_total = (ov_pcm_total_fcn)::ov_pcm_total; g_ov_read = (ov_read_fcn)::ov_read; #endif m_device = alcOpenDevice()(0); if(!m_device) { zero_handles(); FreeLibrary(m_libvorbisfile); FreeLibrary(m_openal32); throw Sound_Init_Failure(); } m_context = alcCreateContext()(m_device, 0); if(!m_context) { alcCloseDevice()(m_device); zero_handles(); FreeLibrary(m_libvorbisfile); FreeLibrary(m_openal32); throw Sound_Init_Failure(); } if(!alcMakeContextCurrent()(m_context)) { alcDestroyContext()(m_context); alcCloseDevice()(m_device); zero_handles(); FreeLibrary(m_libvorbisfile); FreeLibrary(m_openal32); throw Sound_Init_Failure(); } // Check for Vorbis extension functionality; seems to always fail :( alIsExtensionPresent()("AL_EXT_vorbis"); //cerr << "Valid Audio Formats: " << alutGetMIMETypes(ALUT_LOADER_BUFFER) << std::endl; ALfloat listener_position[] = {0.0f, 0.0f, 0.0f}; ALfloat listener_velocity[] = {0.0f, 0.0f, 0.0f}; ALfloat listener_forward_and_up[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; alListenerfv()(AL_POSITION, listener_position); alListenerfv()(AL_VELOCITY, listener_velocity); alListenerfv()(AL_ORIENTATION, listener_forward_and_up); }
Sound::Sound(char* filePath){ path = filePath; //Loading of the WAVE file fp=fopen(filePath,"rb"); //Open the WAVE file if (!fp) endWithError(errors[0]); //Could not open file //Check that the WAVE file is OK fread(&riff_header, sizeof(RIFF_Header), 1, fp); if(riff_header.chunkID[0]!='R' || riff_header.chunkID[1]!='I' || riff_header.chunkID[2]!='F' || riff_header.chunkID[3]!='F') //Should be "RIFF" endWithError (errors[1]); //Not RIFF if (riff_header.format[0]!='W' || riff_header.format[1]!='A' || riff_header.format[2]!='V' || riff_header.format[3]!='E') //This part should be "WAVE" endWithError(errors[2]); //Not WAVE fread(&wave_format, sizeof(WAVE_Format), 1, fp); if (wave_format.subChunkID[0]!='f' || wave_format.subChunkID[1]!='m' || wave_format.subChunkID[2]!='t' || wave_format.subChunkID[3]!=' ') //This part should be "fmt " endWithError(errors[3]); //Not fmt fread(type,sizeof(char),4,fp); if (type[0]!='d' || type[1]!='a' || type[2]!='t' || type[3]!='a') //This part should be "data" endWithError(errors[4]); //not data fread(&dataSize,sizeof(int),1,fp); //The size of the sound data is read buf= new unsigned char[dataSize]; //Allocate memory for the sound data cout << fread(buf,1,dataSize,fp) << " bytes loaded\n"; //Read the sound data and display the //number of bytes loaded. //Should be the same as the Data Size if OK device = alcOpenDevice(NULL); //Open the device if(!device) endWithError(errors[5]); //Error during device oening context = alcCreateContext(device, NULL); //Give the device a context alcMakeContextCurrent(context); //Make the context the current if(!context) endWithError(errors[6]); //Error during context handeling //Stores the sound data frequency=wave_format.sampleRate;; //The Sample Rate of the WAVE file alGenBuffers(1, &buffer); //Generate one OpenAL Buffer and link to "buffer" alGenSources(1, &source); //Generate one OpenAL Source and link to "source" if(alGetError() != AL_NO_ERROR) endWithError("Error GenSource"); //Error during buffer/source generation //Figure out the format of the WAVE file std::cout<<wave_format.numChannels; if(wave_format.bitsPerSample == 8) { if(wave_format.numChannels == 1) format = AL_FORMAT_MONO8; else if(wave_format.numChannels == 2) format = AL_FORMAT_STEREO8; } else if(wave_format.bitsPerSample == 16) { if(wave_format.numChannels == 1) format = AL_FORMAT_MONO16; else if(wave_format.numChannels == 2) format = AL_FORMAT_STEREO16; } if(!format) endWithError(errors[7]); //Not valid format alBufferData(buffer, format, buf, dataSize, frequency); //Store the sound data in the OpenAL Buffer if(alGetError() != AL_NO_ERROR) endWithError(errors[8]); //Error during buffer loading //Sound setting variables ALfloat SourcePos[] = { 0.0, 0.0, 0.0 }; ALfloat SourceVel[] = { 0.0, 0.0, 0.0 }; ALfloat ListenerPos[] = { 0.0, 0.0, 0.0 }; ALfloat ListenerVel[] = { 0.0, 0.0, 0.0 }; ALfloat ListenerOri[] = { 0.0, 0.0, -1.0, 0.0, 1.0, 0.0 }; //First direction vector, then vector pointing up) //Listener alListenerfv(AL_POSITION, ListenerPos); alListenerfv(AL_VELOCITY, ListenerVel); alListenerfv(AL_ORIENTATION, ListenerOri); //Source alSourcei (source, AL_BUFFER, buffer); alSourcef (source, AL_PITCH, 1.0f ); alSourcef (source, AL_GAIN, 1.0f ); alSourcefv(source, AL_POSITION, SourcePos); alSourcefv(source, AL_VELOCITY, SourceVel); alSourcei (source, AL_LOOPING, AL_FALSE ); }
int main() { // GLFWの初期化 if (!glfwInit()) return -1; // GLFW Widnowを用意 GLFWwindow* window = glfwCreateWindow(640, 480, "Play WAV fie", nullptr, nullptr); // Windowsを生成できなければ終了 if (!window) { glfwTerminate(); return -1; } // 用意したWindowsでOpenGLが使えるようにする // これで、OpenGLの命令が有効になる glfwMakeContextCurrent(window); // 描画のタイミングを画面更新と同期 glfwSwapInterval(1); // OpenALの初期化 ALCdevice* device = alcOpenDevice(nullptr); ALCcontext* context = alcCreateContext(device, nullptr); alcMakeContextCurrent(context); // バッファの生成 ALuint buffer_id; alGenBuffers(1, &buffer_id); // WAVデータを読み込む Wav sound("res/lovelive.wav"); // 読み込んだWAVデータの波形をバッファにコピー alBufferData(buffer_id, // ステレオ or モノラル sound.isStereo() ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16, sound.data(), // リニアPCM形式データ sound.size(), // サイズ(バイト数) sound.sampleRate()); // サンプリングレート // ソースの生成 ALuint source_id; alGenSources(1, &source_id); // ソースに再生したいバッファを割り当てる alSourcei(source_id, AL_BUFFER, buffer_id); // ピッチ変更 alSourcef(source_id, AL_PITCH, -1.0); // ループ再生ON alSourcei(source_id, AL_LOOPING, AL_TRUE); // ソースの再生開始 alSourcePlay(source_id); // Windowが閉じられるまで繰り返す while (!glfwWindowShouldClose(window)) { // 描画領域をクリア glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); // 画面とバックバッファを入れ替える glfwSwapBuffers(window); // キー入力などのイベント処理 glfwPollEvents(); } // ソースの破棄 alDeleteSources(1, &source_id); // バッファの破棄 alDeleteBuffers(1, &buffer_id); // OpenALの後始末 alcMakeContextCurrent(nullptr); alcDestroyContext(context); alcCloseDevice(device); // GLFWの後始末 glfwTerminate(); return 0; }
static gboolean gst_openal_sink_prepare (GstAudioSink * audiosink, GstAudioRingBufferSpec * spec) { GstOpenALSink *sink = GST_OPENAL_SINK (audiosink); ALCcontext *context, *old; if (sink->default_context && !gst_openal_sink_unprepare (audiosink)) return FALSE; if (sink->user_context) context = sink->user_context; else { ALCint attribs[3] = { 0, 0, 0 }; /* Don't try to change the playback frequency of an app's device */ if (!sink->user_device) { attribs[0] = ALC_FREQUENCY; attribs[1] = GST_AUDIO_INFO_RATE (&spec->info); attribs[2] = 0; } context = alcCreateContext (sink->default_device, attribs); if (!context) { GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, ("Unable to prepare device."), GST_ALC_ERROR (sink->default_device)); return FALSE; } } old = pushContext (context); if (sink->user_source) { if (!sink->user_context || !alIsSource (sink->user_source)) { GST_ELEMENT_ERROR (sink, RESOURCE, NOT_FOUND, (NULL), ("Invalid source specified for context")); goto fail; } sink->default_source = sink->user_source; } else { ALuint source; alGenSources (1, &source); if (checkALError () != AL_NO_ERROR) { GST_ELEMENT_ERROR (sink, RESOURCE, NO_SPACE_LEFT, (NULL), ("Unable to generate source")); goto fail; } sink->default_source = source; } gst_openal_sink_parse_spec (sink, spec); if (sink->format == AL_NONE) { GST_ELEMENT_ERROR (sink, RESOURCE, SETTINGS, (NULL), ("Unable to get type %d, format %d, and %d channels", spec->type, GST_AUDIO_INFO_FORMAT (&spec->info), GST_AUDIO_INFO_CHANNELS (&spec->info))); goto fail; } sink->buffers = g_malloc (sink->buffer_count * sizeof (*sink->buffers)); if (!sink->buffers) { GST_ELEMENT_ERROR (sink, RESOURCE, FAILED, ("Out of memory."), ("Unable to allocate buffers")); goto fail; } alGenBuffers (sink->buffer_count, sink->buffers); if (checkALError () != AL_NO_ERROR) { GST_ELEMENT_ERROR (sink, RESOURCE, NO_SPACE_LEFT, (NULL), ("Unable to generate %d buffers", sink->buffer_count)); goto fail; } sink->buffer_idx = 0; popContext (old, context); sink->default_context = context; return TRUE; fail: if (!sink->user_source && sink->default_source) alDeleteSources (1, &sink->default_source); sink->default_source = 0; g_free (sink->buffers); sink->buffers = NULL; sink->buffer_count = 0; sink->buffer_length = 0; popContext (old, context); if (!sink->user_context) alcDestroyContext (context); return FALSE; }
void SetupSound() { unsigned char buf[BUFFER_SIZE]; int i; // Get handle to device. pDevice = alcOpenDevice(NULL); if(checkALCError()) { fprintf(stderr, "[SPU] alcOpenDevice failed.\n"); return; } // ALC info. const ALCubyte* UNUSED_VARIABLE deviceName = (ALCubyte*)alcGetString(pDevice, ALC_DEVICE_SPECIFIER); //printf("[SPU] ALC_DEVICE_SPECIFIER = %s.\n", deviceName); const ALCubyte* UNUSED_VARIABLE extensionList = (ALCubyte*)alcGetString(pDevice, ALC_EXTENSIONS); //printf("[SPU] ALC_EXTENSIONS = %s.\n", extensionList); // Create audio context. pContext = alcCreateContext(pDevice, NULL); if(checkALCError()) { fprintf(stderr, "[SPU] alcCreateContext failed.\n"); return; } // Set active context. alcMakeContextCurrent( pContext ); if( checkALCError() ) { fprintf(stderr, "[SPU] alcMakeContextCurrent failed.\n"); return; } // AL info. const ALubyte* UNUSED_VARIABLE version = (ALubyte*)alGetString(AL_VERSION); //printf("[SPU] AL_VERSION = %s.\n", version); const ALubyte* UNUSED_VARIABLE renderer = (ALubyte*)alGetString(AL_RENDERER); //printf("[SPU] AL_RENDERER = %s.\n", renderer); const ALubyte* UNUSED_VARIABLE vendor = (ALubyte*)alGetString(AL_VENDOR); //printf("[SPU] AL_VENDOR = %s.\n", vendor); // Create buffers. alGenBuffers(BUFFER_QUANTITY, buffers); checkALError(); // Load sound data into a buffer. memset(buf, 0x00, BUFFER_SIZE); for(i = 0; i < BUFFER_QUANTITY; ++i) { alBufferData(buffers[i], format, buf, BUFFER_SIZE, sampleRate); } checkALError(); // Create source. alGenSources(1, &source); checkALError(); // Bind buffer with a source. alSourcef (source, AL_PITCH, 1.0f ); alSourcef (source, AL_GAIN, 1.0f ); alSourcefv(source, AL_POSITION, SourcePos); alSourcefv(source, AL_VELOCITY, SourceVel); alSourcefv(source, AL_DIRECTION, SourceDir); alSourcei (source, AL_SOURCE_RELATIVE, AL_TRUE ); alSourcei (source, AL_LOOPING, AL_FALSE ); // Listener properties. alListenerfv(AL_POSITION, ListenerPos); alListenerfv(AL_VELOCITY, ListenerVel); alListenerfv(AL_ORIENTATION, ListenerOri); // Add buffers to queue. alSourceQueueBuffers(source, BUFFER_QUANTITY, buffers); checkALError(); // Enable playing. alSourcePlay(source); checkALError(); }
int main( int argc, char* argv[] ) { ALCdevice *dev; time_t shouldend; int attrlist[] = { ALC_FREQUENCY, DEFFREQ, ALC_INVALID }; char *musicitr = musicstr; ALfloat pitch = 1.0; int beats; char note; dev = alcOpenDevice( NULL ); if( dev == NULL ) { return 1; } cc = alcCreateContext( dev, attrlist); if(cc == NULL) { alcCloseDevice( dev ); return 1; } alcMakeContextCurrent( cc ); fixup_function_pointers(); if(argc == 1) { init(WAVEFILE); } else { init(argv[1]); } while(*musicitr) { alSourceStop( moving_source ); while(*musicitr == ' ') { musicitr++; } switch(*musicitr) { case 'c': pitch = 0.500010; break; case 'd': pitch = 0.561223; break; case 'e': pitch = 0.629967; break; case 'f': pitch = 0.667425; break; case 'g': pitch = 0.749164; break; case 'a': pitch = 0.840898; break; case 'b': pitch = 0.943870; break; case 'C': pitch = 1.0; break; case 'D': pitch = 1.122465; break; case 'E': pitch = 1.259933; break; case 'F': pitch = 1.339704; break; case 'G': pitch = 1.498309; break; case 'A': pitch = 1.681796; break; case 'B': pitch = 1.897754; break; default: fprintf(stderr, "unknown note %d\n", *musicitr); break; } note = *musicitr; musicitr++; /* skip note */ while(*musicitr == ' ') { musicitr++; } beats = (int) *musicitr - '0'; musicitr++; fprintf(stderr, "note %c beats %d\n", note, beats); alSourcef(moving_source, AL_PITCH, pitch); alSourcePlay( moving_source ); micro_sleep(beats / 4.0 * 1000000); } cleanup(); alcCloseDevice( dev ); return 0; }
void SND_StartUp() { ALuint sources[SND_MAX_SRCNUM]; int i; /* int attr[] = { ALC_FREQUENCY, 22050, 0 }; */ if( sst_isup ) { __warning( "sound is already up\n" ); return; } if( !((sh_var_t *)SHP_GetVar( "sound" ))->ivalue ) { __named_message( "\tsound disabled\n" ); sst_isup = 0; return; } Vec3dInit( snd_origin, 0.0, 0.0, 0.0 ); alc_ctx = alcCreateContext( NULL ); alcMakeContextCurrent( alc_ctx ); // init listener alListenerfv( AL_POSITION, zeroes ); alListenerfv( AL_VELOCITY, zeroes ); { alListenerfv( AL_ORIENTATION, front ); } // init sources memset( srcs, 0, SND_MAX_SRCNUM * sizeof( snd_source_t )); al_srcnum = alGenSources( SND_MAX_SRCNUM, sources ); if( al_srcnum != SND_MAX_SRCNUM ) { __warning( "got only %d sources\n", al_srcnum ); } for( i = 0; i < al_srcnum; i++ ) { srcs[i].al_source = sources[i]; printf( "source %d: %d\n", i, srcs[i].al_source ); // alSource3f( srcs[i].al_source, AL_POSITION, 0.0, 0.0, 0.0 ); } alAttenuationScale( 0.7 ); snd_num = 0; sst_isup = 1; // if( 1 ) { ALuint sources[2]; ALuint boom, l2; ALsizei size; ALsizei bits; ALsizei freq; ALsizei format; void *wave = NULL; ALuint left = 0; ALuint right = 0; __named_message( "test...\n" ); if( alGenBuffers( 1, &boom ) != 1 ) { fprintf( stderr, "aldemo: couldn't generate buffers\n" ); exit( 1 ); } alutLoadWAV( "boom.wav", &wave, &format, &size, &bits, &freq); alBufferData( boom, format, wave, size, freq ); alSource3f( boom, AL_POSITION, -5.0, 0.0, 0.0 ); alSourcefv( boom, AL_VELOCITY, zeroes ); alSourcefv( boom, AL_ORIENTATION, back ); alSourcei( boom, AL_BUFFER, boom ); alSourcei( boom, AL_LOOPING, AL_FALSE ); alSourcePlay( boom ); alAttenuationScale(0.7); } }