Math Is Fun Forum
  Discussion about math, puzzles, games and fun.   Useful symbols: √ ∞ ≠ ≤ ≥ ≈ ⇒ ∈ Δ θ ∴ ∑ ∫ π -

Login

Username

Password

Not registered yet?

#1 2007-08-27 18:28:42

mikau
Super Member

Offline

Java sound solution

i have yet to find ANY workable solution to add sound effects to a game written in java.

EVERY method i find has some offensive drawback or disadvantage that makes it unacceptable.

Here are a few examples.

One method allows you to load a midi from a file, but a brief loading pause occurs the first time you play the sound. The game stalling briefly evertytime a new sound plays just won't work. One inelegent solution is to play every sound in the game when it loads up. (which you hear)Even if you can tolerate this, it does not allow you to play the sound again until it finishes. I attempted to resolve this by loading an array of sound players that rotates as you play them, so by the time you get back to the first, the sound is finished. Obviously this has complications because the size of the array is dependant on the length of the sounds, etc. But worse, you have to load the same sound file multiple times on creation, about 4 seconds per sound it took for me, when you have lots of sounds it can take a while to load, and its just lame and wierd to hear all the sounds machine-gunning out when the game starts. (Oh my gosh this game is busted!)

There was another method which i think used the class AudioClip which did allow you to play a sound even before the last has finished, but if I remember correctly, there was always a quarter second pause before the sound played.  sad

I think i tried like 4 different methods, one fixed the overlapping sound problem, one fixed the loading problem, one fixed the pausing problem, but never all at once!

I'm begining to wonder if i should instead try to prove that no solution exists. sad

Last edited by mikau (2007-08-27 18:29:09)


A logarithm is just a misspelled algorithm.

#2 2007-08-27 20:17:28

MathsIsFun
Administrator

Online

Re: Java sound solution

Use Flash ... SwishMax version 2 is currently in beta testing, and worth looking at when it is released.

The only drawback is if you need a lot of calcs (Flash math speed is quite low).


"The physicists defer only to mathematicians, and the mathematicians defer only to God ..."  - Leon M. Lederman

#3 2007-08-28 03:17:54

Ricky
Moderator

Offline

Re: Java sound solution

Can you paste the code snippets which are used for loading and playing sounds?


"In the real world, this would be a problem.  But in mathematics, we can just define a place where this problem doesn't exist.  So we'll go ahead and do that now..."

#4 2007-08-28 04:13:27

mikau
Super Member

Offline

Re: Java sound solution

two other methods i used had a built in sound player which pretty much hid the details, it just said playSound(file) so i don't think it there's any point in posting those.

But here's one of the methods i used that shows the details. Note, most of this code is copied directly from where i found it.

Code:

import java.io.*;
import sun.audio.*;


public class AudioStreamPlay
{

   // AudioPlayer instantiated to force run of static initializers.
   private AudioPlayer audioPlayer = AudioPlayer.player;
   private AudioDataStream audioDataStream;
   private ContinuousAudioDataStream continuousAudioDataStream;
   // Applet role
   public void AudioStreamPlay()
   {

    try
        {
        // Get sound from file stream.
          FileInputStream fis = new FileInputStream( new File( "soundFile.au") );
          AudioStream as = new AudioStream( fis ); // header plus audio data
          AudioData ad = as.getData(); // audio data only, no header
          audioDataStream = new AudioDataStream( ad );
          continuousAudioDataStream = new ContinuousAudioDataStream( ad );

          }
          catch (Exception exp)
          {
            System.out.println("error! x_x");

        }
   }
   // Component role (1.02 event model)
   public void playSound()
   {
         audioPlayer.start( audioDataStream );

   }

   public void loopSound()
   {
         audioPlayer.start( continuousAudioDataStream );
   }

    public void stopSound()
    {
         audioPlayer.stop( audioDataStream );
         audioPlayer.stop( continuousAudioDataStream );
    }

    public void resetSound()
    {
        continuousAudioDataStream.reset();
    }


}
import java.io.*;
import sun.audio.*;


public class AudioStreamPlay
{

   // AudioPlayer instantiated to force run of static initializers.
   private AudioPlayer audioPlayer = AudioPlayer.player;
   private AudioDataStream audioDataStream;
   private ContinuousAudioDataStream continuousAudioDataStream;
  
   public void AudioStreamPlay()
   {

    try
        {
        // Get sound from file stream.
          FileInputStream fis = new FileInputStream( new File( "soundFile.au") );
          AudioStream as = new AudioStream( fis ); // header plus audio data
          AudioData ad = as.getData(); // audio data only, no header
          audioDataStream = new AudioDataStream( ad );
          continuousAudioDataStream = new ContinuousAudioDataStream( ad );

          }
          catch (Exception exp)
          {
            System.out.println("error! x_x");

        }
   }

   public void playSound()
   {
         audioPlayer.start( audioDataStream );

   }

   public void loopSound()
   {
         audioPlayer.start( continuousAudioDataStream );
   }

    public void stopSound()
    {
         audioPlayer.stop( audioDataStream );
                     audioPlayer.stop( continuousAudioDataStream );
    }

    public void resetSound()
    {
        continuousAudioDataStream.reset();
    }


}

Last edited by mikau (2007-08-28 04:14:02)


A logarithm is just a misspelled algorithm.

#5 2007-08-29 09:14:07

mikau
Super Member

Offline

Re: Java sound solution

in the meantime, here's another problem concerning java that i've just been faced with. I figured i'd post it here rather than making a new thread for every problem i run into.

I'm working on a small collection of abstract classes to help facilitate 2d game development by providing the basic class structures with a collection of the most common functions.

There is a class GameEnvironment which specifies the most general properties of the game,
a class RoomObject which is like a playing board for the objects in the game, and there is a class GameObject which represents any object in the game with x,y coordinates and a sprite image. (and a few more conveniences)

anyway, each RoomObject has an array of GameObjects which holds all the objects that exist in that room.  I want to write a function that will colllect all the objects of a specified type from that array, (specified by the function argument) and then return an array of those objects so i can toss that array to a collision checker function. The only problem is i pretty much require the instance of operator, and this takes the name of a class as an operand (not in string form)

so I can't really specify which objects to extract from the array. While I could seek some alternative to instanceof, the advantage of using instanceof is that it will pick up subclasses of a given class, so i can, technically, check for a collision against a more general type of object and implicitly pick up all subclasses that exist in the array for a collision check.

I just can't supply the class name as an argument, as far as i know.
An alternative is to use the getClass() function to compare objects of two separate classes, but unfortunately, the objects must be instantiated, so you can't see if one object is an instace of an abstract class.


A logarithm is just a misspelled algorithm.

#6 2007-08-30 02:37:55

Ricky
Moderator

Offline

Re: Java sound solution

The code you posted looks like it should work just fine.  Why is it that you have to play a sound when the program starts up to not cause a delay later?

As for your polymorphism problem, the solution is to put a string in the GameObject class, it's value being the type of object.  While you're at it, I would also include an integer "id" which is unique across all objects.  This typically simplifies debugging.  I haven't done Java in like 2 years, but I believe there should be some use of static that spans across classes and throughout execution time.  In c++, you would do in your constructor:

static int idnum = 1;
Class.id = idnum;
idnum++;


"In the real world, this would be a problem.  But in mathematics, we can just define a place where this problem doesn't exist.  So we'll go ahead and do that now..."

#7 2007-08-30 02:53:42

mikau
Super Member

Offline

Re: Java sound solution

The problem is the first time it plays, it has to load the sound file from the system, which takes a moment. i'd really rather do it at game creation rather than play time. Otherwise, like i said, the game pauses briefly every time a new sound plays.

And i can't replay a sound until the first has stopped playing. As I mentioned i created a rotater to play multiple sounds in a row but then it takes 4-8 times longer to load.

as for the other topic,
i have already assigned each class a string name, in fact getRoomObjectClassName() and getGameObjectClassName() are abstract methods in each classs to ensure they are implemented. each game object also has a unique integer id that it gets from the environment in pretty much the exact way you describe.

an idea i had to do was to create a 2 dimensional array to hold room objects, 1 dimension for class types, and one dimension for objects of that type. To get a particular class object array, i'd give the string name of the class to the array, it would search the rows for the class with that string name, and then return that row. Likewise, whenever an object is created, its named would be used to find which row it belongs to before being added to the arrray.

My only concern here is string comparison and doing lots of array searching. x_x I hate having to do lots of array handling in an application where speed is essential.


A logarithm is just a misspelled algorithm.

#8 2007-08-30 03:17:58

Ricky
Moderator

Offline

Re: Java sound solution

Don't quite see what exactly the problem is.  You can just use the Class.forName method:

String s = "Ball";
Ball b;

if (Class.forName(s).isInstance(b)) { //this will result in true


"In the real world, this would be a problem.  But in mathematics, we can just define a place where this problem doesn't exist.  So we'll go ahead and do that now..."

#9 2007-08-30 10:32:31

mikau
Super Member

Offline

Re: Java sound solution

i believe that doesn't work if, for instance, b were a subclass of ball.


A logarithm is just a misspelled algorithm.

#10 2007-08-31 05:28:35

mikau
Super Member

Offline

Re: Java sound solution

anyway, i seemed to have resolved the issue by resorting to string comparisons for array processing. I don't like doing this but it seems to be the easiest way out. I wonder if string comparison really takes as long as i fear...

the other issue of picking up subclasses, i'm just going to have to write a for loop and 'instanceof' whenever i need it, rather than using a calling function to do it for me. Not the prettiest thing but it works, and fortunately i don't need it very often.

but Sound is still an issue. What I need is a way to load the sound once and only once to minimize the interaction with the system and retrieving files, and then somehow be able to play that sound more than once at a time.


A logarithm is just a misspelled algorithm.

#11 2008-05-02 15:44:40

jakster4u
Novice

Offline

Re: Java sound solution

This is what I am doing for sound, it loads each file at the start but my problem is that if I try to load too much I get an error.
java.lang.OutOfMemoryError: Java heap space

Code:

//initialization
AudioClip soundTokyo;
AudioClip soundGame;
URL u = RiskCanvas.class.getResource( "music\\livefromkyoto-moonless-dawn.wav" );
          if ( u == null )
             {
             throw new IllegalArgumentException ( "music file missing" );
             }
          soundTokyo = getAudioClip( u );
          u = RiskCanvas.class.getResource( "music\\trip-warhawkins-stolen-gamecube.wav" );
          if ( u == null )
             {
             throw new IllegalArgumentException ( "music file missing" );
             }
          soundGame = getAudioClip( u );
//====================================================================
//when I go to play one I make sure the other is stopped and start looping the next
if()
soundGame.stop();
soundTokyo.loop();
else
soundTokyo.stop();
soundGame.loop();

Right now I am using it play background music that the user can pick from in a menu. But if I can't find a way to load them without error, I might have to use it for sound effects instead of the large wav files I am currently using.

#12 2008-05-03 00:13:33

Ricky
Moderator

Offline

Re: Java sound solution

Always go to the source...

http://java.sun.com/docs/books/tutorial … aying.html

That *should* allow you to play multiple files at once.


"In the real world, this would be a problem.  But in mathematics, we can just define a place where this problem doesn't exist.  So we'll go ahead and do that now..."

#13 2008-05-10 12:13:40

John E. Franklin
Star Member

Offline

Re: Java sound solution

Also you can tinker with port 61, the old PC speaker!!


igloo myrtilles fourmis

Board footer

Powered by FluxBB