OpenAL demo

Started by Evan407, January 11, 2017, 21:01:30

Previous topic - Next topic

Evan407

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();}}
}

spasi

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).