int obtainSource(boolean isMusic) { if (noDevice) return 0; for (int i = 0, n = idleSources.size; i < n; i++) { int sourceId = idleSources.get(i); int state = alGetSourcei(sourceId, AL_SOURCE_STATE); if (state != AL_PLAYING && state != AL_PAUSED) { if (isMusic) { idleSources.removeIndex(i); } else { if (sourceToSoundId.containsKey(sourceId)) { long soundId = sourceToSoundId.get(sourceId); sourceToSoundId.remove(sourceId); soundIdToSource.remove(soundId); } long soundId = nextSoundId++; sourceToSoundId.put(sourceId, soundId); soundIdToSource.put(soundId, sourceId); } alSourceStop(sourceId); alSourcei(sourceId, AL_BUFFER, 0); AL10.alSourcef(sourceId, AL10.AL_GAIN, 1); AL10.alSourcef(sourceId, AL10.AL_PITCH, 1); AL10.alSource3f(sourceId, AL10.AL_POSITION, 0, 0, 1f); return sourceId; } } return -1; }
public void setVolume(float volume) { this.baseVol = volume; if (this.type == 0) AL10.alSourcef(this.src, AL10.AL_GAIN, volume * ((float) Globals.getSoundVolume() / 100.0f)); else AL10.alSourcef(this.src, AL10.AL_GAIN, volume * ((float) Globals.getMusicVolume() / 100.0f)); }
/** * Play the specified buffer as music (i.e. use the music channel) * * @param buffer The buffer to be played * @param pitch The pitch to play the music at * @param gain The gaing to play the music at * @param loop True if we should loop the music */ void playAsMusic(int buffer, float pitch, float gain, boolean loop) { paused = false; setMOD(null); if (soundWorks) { if (currentMusic != -1) { AL10.alSourceStop(sources.get(0)); } getMusicSource(); AL10.alSourcei(sources.get(0), AL10.AL_BUFFER, buffer); AL10.alSourcef(sources.get(0), AL10.AL_PITCH, pitch); AL10.alSourcei(sources.get(0), AL10.AL_LOOPING, loop ? AL10.AL_TRUE : AL10.AL_FALSE); currentMusic = sources.get(0); if (!music) { pauseLoop(); } else { AL10.alSourcePlay(sources.get(0)); } } }
public void execute() { // Initialize OpenAL and clear the error bit. try { AL.create(); } catch (LWJGLException le) { le.printStackTrace(); return; } AL10.alGetError(); // Load the wav data. if (loadALData() == AL10.AL_FALSE) { System.out.println("Error loading data."); return; } setListenerValues(); // Loop. System.out.println("OpenAL Tutorial 1 - Single Static Source"); System.out.println("[Menu]"); System.out.println("p - Play the sample."); System.out.println("s - Stop the sample."); System.out.println("h - Pause the sample."); System.out.println("q - Quit the program."); char c = ' '; Scanner stdin = new Scanner(System.in); while (c != 'q') { try { System.out.print("Input: "); c = (char) stdin.nextLine().charAt(0); } catch (Exception ex) { c = 'q'; } switch (c) { // Pressing 'p' will begin playing the sample. case 'p': AL10.alSourcePlay(source.get(0)); break; // Pressing 's' will stop the sample from playing. case 's': AL10.alSourceStop(source.get(0)); break; // Pressing 'h' will pause the sample. case 'h': AL10.alSourcePause(source.get(0)); break; } ; } killALData(); AL.destroy(); }
public void UpdateListener(float x, float y, float z, float vx, float vy, float vz) { FloatBuffer listenerVel = BufferUtils.createFloatBuffer(3).put(new float[] {vx, vy, vz}); FloatBuffer listenerPos = BufferUtils.createFloatBuffer(3).put(new float[] {x, y, z}); listenerPos.flip(); listenerVel.flip(); AL10.alListener(AL10.AL_POSITION, listenerPos); AL10.alListener(AL10.AL_VELOCITY, listenerVel); listenerPosX = x; listenerPosY = y; }
void updateSource(int source, float x, float y, float z, float vx, float vy, float vz) { sourcePos.clear(); sourceVel.clear(); sourceVel.put(new float[] {vx, vy, vz}); sourcePos.put(new float[] {x, y, z}); sourcePos.flip(); sourceVel.flip(); AL10.alSource(sources.get(source), AL10.AL_POSITION, sourcePos); AL10.alSource(sources.get(source), AL10.AL_VELOCITY, sourceVel); }
/** Deletes any sources and clears out the sound store contents */ public void clear() { if (sources != null && AL.isCreated()) { for (int i = 0; i < sourceCount; i++) { int src = sources.get(i); AL10.alSourcei(src, AL10.AL_BUFFER, 0); AL10.alSourceStop(src); AL10.alDeleteSources(src); } } store = new SoundStore(); }
public void setSoundPan(long soundId, float pan, float volume) { if (!soundIdToSource.containsKey(soundId)) return; int sourceId = soundIdToSource.get(soundId); AL10.alSource3f( sourceId, AL10.AL_POSITION, MathUtils.cos((pan - 1) * MathUtils.PI / 2), 0, MathUtils.sin((pan + 1) * MathUtils.PI / 2)); AL10.alSourcef(sourceId, AL10.AL_GAIN, volume); }
@Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { if (map != null) super.render(gc, sbg, g); font.drawString(4 * gc.getWidth() / 5, 30, "" + Globals.score); Utils.drawCenteredString( g, "Cursors - Move Ctrl - Jump B - Show Bounds R - Restart", gc.getWidth(), gc.getHeight() - 20, Color.black); /*for (int i = 0; i < map.getWorld().getBodies().size(); i++) { if (map.getEntityByBody(map.getWorld().getBodies().get(i)) instanceof HomerIA) { sound.setSourcePosition((map.getEntityByBody( map.getWorld().getBodies().get(i)).getX() - map .getEntityByBody(map.getWorld().getBodies().get(i)) .getWidth() / 2), (map.getEntityByBody( map.getWorld().getBodies().get(i)).getY() - map .getEntityByBody(map.getWorld().getBodies().get(i)) .getHeight() / 2), 0f); } }*/ // We put the openAl listener's position and velocity AlUtils.setAlListenerPosition( Globals.player.getX() - Globals.player.getWidth() / 2, Globals.player.getY() - Globals.player.getHeight() / 2, 0.0f); AlUtils.setAlListenerVelocity(Globals.player.getVelX() * 5, -Globals.player.getVelY(), 0.0f); // sound.setSourceVelocity(10f, 0f, 0f, soundIndex); // AlUtils.resetAlListener(); if (AL10.alGetError() != AL10.AL_NO_ERROR) System.out.println("Erreur d'OpenAL" + AL10.alGetError()); // Environment sounds if (soundWalk != null) soundWalk(); soundBump(); soundGround(); soundJump(); // we execute permanentSound method for all the enemy for (int i = 0; i < map.getWorld().getBodies().size(); i++) { if (map.getEntityByBody(map.getWorld().getBodies().get(i)) instanceof Enemy) { ((Enemy) map.getEntityByBody(map.getWorld().getBodies().get(i))).permanentSound(i); } } // the help sound if executed helpSound.setSourcePosition( Globals.player.getX() - Globals.player.getWidth() / 2, Globals.player.getY() - Globals.player.getHeight() / 2, 0.0f); }
public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException { // The listener is reset AlUtils.resetAlListener(); // the orientation is changed AlUtils.setAlListenerOrientation(0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f); // we set sound context AL10.alDistanceModel(AL11.AL_EXPONENT_DISTANCE); AL10.alDopplerFactor(0.8f); // We play the two sounds since we enter sonG.loop(1f, 1f, 0f, 0f, 0f); sonD.loop(1f, 1f, 0f, 0f, 0f); AL10.alSourcef(sonG.getIndex(), AL10.AL_ROLLOFF_FACTOR, 1.5f); AL10.alSourcef(sonD.getIndex(), AL10.AL_ROLLOFF_FACTOR, 1.5f); // We play the beginning explanation sound enterSound.play(); }
/** * Get the Sound based on a specified OGG file * * @param ref The reference to the OGG file in the classpath * @param in The stream to the OGG to load * @return The Sound read from the OGG file * @throws IOException Indicates a failure to load the OGG */ public Audio getOgg(String ref, InputStream in) throws IOException { if (!soundWorks) { return new NullAudio(); } if (!inited) { throw new RuntimeException( "Can't load sounds until SoundStore is init(). Use the container init() method."); } if (deferred) { return new DeferredSound(ref, in, DeferredSound.OGG); } int buffer = -1; if (loaded.get(ref) != null) { buffer = ((Integer) loaded.get(ref)).intValue(); } else { try { IntBuffer buf = BufferUtils.createIntBuffer(1); OggDecoder decoder = new OggDecoder(); OggData ogg = decoder.getData(in); AL10.alGenBuffers(buf); AL10.alBufferData( buf.get(0), ogg.channels > 1 ? AL10.AL_FORMAT_STEREO16 : AL10.AL_FORMAT_MONO16, ogg.data, ogg.rate); loaded.put(ref, new Integer(buf.get(0))); buffer = buf.get(0); } catch (Exception e) { Log.error(e); Log.info("Failed to load: " + ref + " - " + e.getMessage()); throw new IOException("Unable to load: " + ref); } } if (buffer == -1) { throw new IOException("Unable to load: " + ref); } return new AudioImpl(this, buffer); }
/** * Check if the music is currently playing * * @return True if the music is playing */ public boolean isMusicPlaying() { if (!soundWorks) { return false; } int state = AL10.alGetSourcei(sources.get(0), AL10.AL_SOURCE_STATE); return ((state == AL10.AL_PLAYING) || (state == AL10.AL_PAUSED)); }
@Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { super.init(gc, sbg); input = gc.getInput(); soundJump = new Sound2(Conf.SND_BIP_PATH + "bip6.ogg"); soundJump2 = new Sound2(Conf.SND_DEPLACEMENT_PATH + "saut.ogg"); soundBump = new Sound2(Conf.SND_DEPLACEMENT_PATH + "bump.ogg"); killedEnemySound = new Sound2(Conf.SND_PERSOS_PATH + "hurt_light2.ogg"); helpSound = new Sound2(Conf.getVoice("jeuf1")); font = new AngelCodeFont(Conf.FONTS_PATH + "hiero.fnt", Conf.FONTS_PATH + "hiero.png"); // We set Open Al constants about physical world AL10.alDopplerFactor(1.0f); // Doppler effect AL10.alDopplerVelocity(1.0f); // Sound speed AL10.alDistanceModel(AL11.AL_EXPONENT_DISTANCE); AL10.alDopplerFactor(50.0f); }
/** * Get the Sound based on a specified AIF file * * @param ref The reference to the AIF file in the classpath * @param in The stream to the AIF to load * @return The Sound read from the AIF file * @throws IOException Indicates a failure to load the AIF */ public Audio getAIF(String ref, InputStream in) throws IOException { in = new BufferedInputStream(in); if (!soundWorks) { return new NullAudio(); } if (!inited) { throw new RuntimeException( "Can't load sounds until SoundStore is init(). Use the container init() method."); } if (deferred) { return new DeferredSound(ref, in, DeferredSound.AIF); } int buffer = -1; if (loaded.get(ref) != null) { buffer = ((Integer) loaded.get(ref)).intValue(); } else { try { IntBuffer buf = BufferUtils.createIntBuffer(1); AiffData data = AiffData.create(in); AL10.alGenBuffers(buf); AL10.alBufferData(buf.get(0), data.format, data.data, data.samplerate); loaded.put(ref, new Integer(buf.get(0))); buffer = buf.get(0); } catch (Exception e) { Log.error(e); IOException x = new IOException("Failed to load: " + ref); x.initCause(e); throw x; } } if (buffer == -1) { throw new IOException("Unable to load: " + ref); } return new AudioImpl(this, buffer); }
/** * Find a free sound source * * @return The index of the free sound source */ private int findFreeSource() { for (int i = 1; i < sourceCount - 1; i++) { int state = AL10.alGetSourcei(sources.get(i), AL10.AL_SOURCE_STATE); if ((state != AL10.AL_PLAYING) && (state != AL10.AL_PAUSED)) { return i; } } return -1; }
/** * Set the music volume of the current playing music. Does NOT affect the global volume * * @param volume The volume for the current playing music */ public void setCurrentMusicVolume(float volume) { if (volume < 0) { volume = 0; } if (volume > 1) { volume = 1; } if (soundWorks) { lastCurrentMusicVolume = volume; AL10.alSourcef(sources.get(0), AL10.AL_GAIN, lastCurrentMusicVolume * musicVolume); } }
@Override public void update(float dt) { super.update(dt); Vector3f pos = getPosition(); Vector3f vel = getCurrVelocity(); Vector3f up = getUpVector(); Vector3f dir = getFacingVector(); AL10.alListener3f(AL10.AL_POSITION, pos.x, pos.y, pos.z); AL10.alListener3f(AL10.AL_VELOCITY, vel.x, vel.y, vel.z); orientBuf.rewind(); orientBuf.put(dir.x); orientBuf.put(dir.y); orientBuf.put(dir.z); orientBuf.put(up.x); orientBuf.put(up.y); orientBuf.put(up.z); orientBuf.rewind(); AL10.alListener(AL10.AL_ORIENTATION, orientBuf); }
/** * Get the Sound based on a specified OGG file * * @param ref The reference to the OGG file in the classpath * @return The Sound read from the OGG file * @throws IOException Indicates a failure to load the OGG */ public Audio getOggStream(URL ref) throws IOException { if (!soundWorks) { return new NullAudio(); } setMOD(null); setStream(null); if (currentMusic != -1) { AL10.alSourceStop(sources.get(0)); } getMusicSource(); currentMusic = sources.get(0); return new StreamSound(new OpenALStreamPlayer(currentMusic, ref)); }
/** * Stops and releases all sources, clears each of the specified Audio buffers, destroys the OpenAL * context, and resets SoundStore for future use. * * <p>Calling SoundStore.get().init() will re-initialize the OpenAL context after a call to * destroyOpenAL (Note: AudioLoader.getXXX calls init for you). * * @author davedes (http://slick.ninjacave.com/forum/viewtopic.php?t=3920) */ private static void destroyOpenAL() { if (!trackExists()) return; stop(); try { // get Music object's (private) Audio object reference Field sound = player.getClass().getDeclaredField("sound"); sound.setAccessible(true); Audio audio = (Audio) (sound.get(player)); // first clear the sources allocated by SoundStore int max = SoundStore.get().getSourceCount(); IntBuffer buf = BufferUtils.createIntBuffer(max); for (int i = 0; i < max; i++) { int source = SoundStore.get().getSource(i); buf.put(source); // stop and detach any buffers at this source AL10.alSourceStop(source); AL10.alSourcei(source, AL10.AL_BUFFER, 0); } buf.flip(); AL10.alDeleteSources(buf); int exc = AL10.alGetError(); if (exc != AL10.AL_NO_ERROR) { throw new SlickException("Could not clear SoundStore sources, err: " + exc); } // delete any buffer data stored in memory, too... if (audio != null && audio.getBufferID() != 0) { buf = BufferUtils.createIntBuffer(1).put(audio.getBufferID()); buf.flip(); AL10.alDeleteBuffers(buf); exc = AL10.alGetError(); if (exc != AL10.AL_NO_ERROR) { throw new SlickException( "Could not clear buffer " + audio.getBufferID() + ", err: " + exc); } } // clear OpenAL AL.destroy(); // reset SoundStore so that next time we create a Sound/Music, it will reinit SoundStore.get().clear(); player = null; } catch (Exception e) { ErrorHandler.error("Failed to destroy OpenAL.", e, true); } }
/** * Play the specified buffer as a sound effect with the specified pitch and gain. * * @param buffer The ID of the buffer to play * @param pitch The pitch to play at * @param gain The gain to play at * @param loop True if the sound should loop * @param x The x position to play the sound from * @param y The y position to play the sound from * @param z The z position to play the sound from * @return source The source that will be used */ int playAsSoundAt(int buffer, float pitch, float gain, boolean loop, float x, float y, float z) { gain *= soundVolume; if (gain == 0) { gain = 0.001f; } if (soundWorks) { if (sounds) { int nextSource = findFreeSource(); if (nextSource == -1) { return -1; } AL10.alSourceStop(sources.get(nextSource)); AL10.alSourcei(sources.get(nextSource), AL10.AL_BUFFER, buffer); AL10.alSourcef(sources.get(nextSource), AL10.AL_PITCH, pitch); AL10.alSourcef(sources.get(nextSource), AL10.AL_GAIN, gain); AL10.alSourcei( sources.get(nextSource), AL10.AL_LOOPING, loop ? AL10.AL_TRUE : AL10.AL_FALSE); sourcePos.clear(); sourceVel.clear(); sourceVel.put(new float[] {0, 0, 0}); sourcePos.put(new float[] {x, y, z}); sourcePos.flip(); sourceVel.flip(); AL10.alSourcefv(sources.get(nextSource), AL10.AL_POSITION, sourcePos); AL10.alSourcefv(sources.get(nextSource), AL10.AL_VELOCITY, sourceVel); AL10.alSourcePlay(sources.get(nextSource)); return nextSource; } } return -1; }
public final synchronized boolean initialize() { if (!this.gpz) { try { AL.create(); bIM(); AL10.alDistanceModel(53252); check(); this.gpz = true; } catch (LWJGLException localLWJGLException) { K.warn( "Probl?me lors de SoundManager.initialize(). Impossible d'initialiser le SoundManager", localLWJGLException); this.gpz = false; this.gpA = true; return false; } } return (!this.aKV) && (blp()); }
public static void check() { int i = AL10.alGetError(); if (i != 0) { String str = "unknown error"; switch (i) { case 40961: str = "AL_INVALID_NAME"; break; case 40962: str = "AL_INVALID_ENUM"; break; case 40963: str = "AL_INVALID_VALUE"; break; case 40964: str = "AL_INVALID_OPERATION"; break; case 40965: str = "AL_OUT_OF_MEMORY"; } throw new OpenALException("OpenAL error : " + str); } }
/** Pause the music loop that is currently playing */ public void pauseLoop() { if ((soundWorks) && (currentMusic != -1)) { paused = true; AL10.alSourcePause(currentMusic); } }
/** * void killALData() * * <p>We have allocated memory for our buffers and sources which needs to be returned to the * system. This function frees that memory. */ void killALData() { AL10.alDeleteSources(source); AL10.alDeleteBuffers(buffer); }
@Override public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException { currentState = States.IN_GAME; Globals.score_submitted = false; // If the "main" previous state was not the game state, then it's // probably the menu state if (Globals.returnState != stateID) { // Globals.stateToGoTo.clear(); Globals.nodes.clear(); Globals.initQuestionsNotAsked(); Globals.started = true; createMap(); LoadingList.setDeferredLoading(false); soundWalk = new Sound2(Globals.player.getSoundWalk()); LoadingList.setDeferredLoading(true); Globals.score = 0; map.setMainPlayer(Globals.player); Globals.player.reinitPosition(); voix = new t2s.SIVOXDevint(); Globals.nodeHasChanged = true; } super.enter(gc, sbg); if (Globals.nodeHasChanged) { // map.addEntity(Globals.getEntityFromCurrentNode()); PhysicalEntity ia = Globals.node.getIA(); if (ia != null) { // we set the ia's position Dimension d = Globals.nodes.poll(); if (d != null) { ia.setPosition((float) d.getWidth(), (float) d.getHeight()); } else { System.err.println("No more node locations available."); } // we set the ia map.addEntity(ia); } else { System.err.println("The current node (" + Globals.node.getID() + ") doesn't have an ia."); Globals.nextEvent(sbg); } Globals.nodeHasChanged = false; } // this state is important so we put it in Globals Globals.returnState = stateID; AL10.alDopplerFactor(1.0f); // we execute enter methods for all the IA for (int i = 0; i < map.getWorld().getBodies().size(); i++) { if (map.getEntityByBody(map.getWorld().getBodies().get(i)) instanceof IA) { ((IA) map.getEntityByBody(map.getWorld().getBodies().get(i))).enter(); } else if (map.getEntityByBody(map.getWorld().getBodies().get(i)) instanceof Enemy) { ((Enemy) map.getEntityByBody(map.getWorld().getBodies().get(i))).enter(); } else if (map.getEntityByBody(map.getWorld().getBodies().get(i)) instanceof Spirit) { ((Spirit) map.getEntityByBody(map.getWorld().getBodies().get(i))).enter(); } } }
/** * boolean LoadALData() * * <p>This function will load our sample data from the disk using the Alut utility and send the * data into OpenAL as a buffer. A source is then also created to play that buffer. */ int loadALData() { // Load wav data into a buffer. AL10.alGenBuffers(buffer); if (AL10.alGetError() != AL10.AL_NO_ERROR) return AL10.AL_FALSE; // Loads the wave file from your file system /*java.io.FileInputStream fin = null; try { fin = new java.io.FileInputStream("FancyPants.wav"); } catch (java.io.FileNotFoundException ex) { ex.printStackTrace(); return AL10.AL_FALSE; } WaveData waveFile = WaveData.create(fin); try { fin.close(); } catch (java.io.IOException ex) { }*/ // Loads the wave file from this class's package in your classpath WaveData waveFile = WaveData.create("FancyPants.wav"); AL10.alBufferData(buffer.get(0), waveFile.format, waveFile.data, waveFile.samplerate); waveFile.dispose(); // Bind the buffer with the source. AL10.alGenSources(source); if (AL10.alGetError() != AL10.AL_NO_ERROR) return AL10.AL_FALSE; AL10.alSourcei(source.get(0), AL10.AL_BUFFER, buffer.get(0)); AL10.alSourcef(source.get(0), AL10.AL_PITCH, 1.0f); AL10.alSourcef(source.get(0), AL10.AL_GAIN, 1.0f); AL10.alSource(source.get(0), AL10.AL_POSITION, sourcePos); AL10.alSource(source.get(0), AL10.AL_VELOCITY, sourceVel); // Do another error check and return. if (AL10.alGetError() == AL10.AL_NO_ERROR) return AL10.AL_TRUE; return AL10.AL_FALSE; }
/** Restart the music loop that is currently paused */ public void restartLoop() { if ((music) && (soundWorks) && (currentMusic != -1)) { paused = false; AL10.alSourcePlay(currentMusic); } }
/** * Stop a playing sound identified by the ID returned from playing. This utility method should * only be used when needing to stop sound effects that may have been played more than once and * need to be explicitly stopped. * * @param id The ID of the underlying OpenAL source as returned from playAsSoundEffect */ public void stopSoundEffect(int id) { AL10.alSourceStop(id); }
/** * void setListenerValues() * * <p>We already defined certain values for the Listener, but we need to tell OpenAL to use that * data. This function does just that. */ void setListenerValues() { AL10.alListener(AL10.AL_POSITION, listenerPos); AL10.alListener(AL10.AL_VELOCITY, listenerVel); AL10.alListener(AL10.AL_ORIENTATION, listenerOri); }
/** * Set the pitch at which the current music is being played * * @param pitch The pitch at which the current music is being played */ public void setMusicPitch(float pitch) { if (soundWorks) { AL10.alSourcef(sources.get(0), AL10.AL_PITCH, pitch); } }