LWJGL Forum

Programming => LWJGL Documentation => Topic started by: Evan407 on January 11, 2017, 21:01:30

Title: OpenAL demo
Post by: Evan407 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.
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();}}
}
Title: Re: OpenAL demo
Post by: spasi on January 15, 2017, 15:22:51
LWJGL has plenty of OpenAL demos, here (https://github.com/LWJGL/lwjgl3/tree/master/modules/core/src/test/java/org/lwjgl/demo/openal). Also, here (https://github.com/LWJGL/lwjgl3/blob/master/modules/core/src/test/java/org/lwjgl/demo/stb/Vorbis.java)'s a Vorbis player written in LWJGL (stb_vorbis for decoding, OpenAL for audio, GLFW and OpenGL for graphics).