LWJGL Forum

Please login or register.

Login with username, password and session length

Author Topic: OpenAL demo  (Read 653 times)

Evan407

  • Newbie
  • *
  • Offline Offline
  • Posts: 42
OpenAL demo
« on: January 11, 2017, 21:01:30 »

I spent today trying to figure out openAL with lwjgl 3. I finally got this quick and dirty demo program to play back a sound.
Code: [Select]
package com.evansgame.newproject;
import static org.lwjgl.openal.AL10.*;
import org.lwjgl.openal.*;
import static org.lwjgl.openal.AL.*;
import static org.lwjgl.openal.ALC.*;
import static org.lwjgl.openal.ALC10.*;
import static javax.sound.sampled.AudioSystem.*;
import java.io.*;
import javax.sound.sampled.*;
import org.lwjgl.BufferUtils;
import java.nio.*;
class SoundTest{
  public static void main(String[] args){try{
AudioInputStream stream = getAudioInputStream(new File("audio.wav"));
AudioFormat format = stream.getFormat();
int alFormat = -1;
if(format.getChannels() == 1){
  if(format.getSampleSizeInBits() == 8){
alFormat = AL_FORMAT_MONO8;
  }else if(format.getSampleSizeInBits() == 16){
alFormat = AL_FORMAT_MONO16;
  }
}else if(format.getChannels() == 2){
  if(format.getSampleSizeInBits() == 8){
alFormat = AL_FORMAT_STEREO8;
  }else if(format.getSampleSizeInBits() == 16){
alFormat = AL_FORMAT_STEREO16 ;
  }
}
if(alFormat == -1)throw new RuntimeException("can't handle format");
byte[] byteArray = new byte[stream.available()];
stream.read(byteArray);
ByteBuffer audioBuffer = BufferUtils.createByteBuffer(byteArray.length);
audioBuffer.put(byteArray);
byteArray = null;
stream.close();
audioBuffer.flip();

long device = alcOpenDevice((java.lang.CharSequence)null);
long context = alcCreateContext(device,(int[])null);
alcMakeContextCurrent(context);
ALCCapabilities alcCapabilities = ALC.createCapabilities(device);
ALCapabilities alCapabilities = AL.createCapabilities(alcCapabilities);
int buffer = alGenBuffers();
alBufferData(buffer, alFormat, audioBuffer, (int)format.getSampleRate());
int source = alGenSources();
alSourcei(source,AL_BUFFER,buffer);
alSourcePlay(source);
Thread.sleep(3000);
alcCloseDevice(device);
  }catch(Exception e){e.printStackTrace();}}
}
Logged

spasi

  • Administrator
  • Nerdus Imperius
  • *****
  • Offline Offline
  • Posts: 1888
Re: OpenAL demo
« Reply #1 on: January 15, 2017, 15:22:51 »

LWJGL has plenty of OpenAL demos, here. Also, here's a Vorbis player written in LWJGL (stb_vorbis for decoding, OpenAL for audio, GLFW and OpenGL for graphics).
Logged