Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (542)
Games in Android Showcase (133)
games submitted by our members
Games in WIP (604)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: 1 [2] 3
  ignore  |  Print  
  Improving EasyOgg  (Read 21588 times)
0 Members and 1 Guest are viewing this topic.
Offline gouessej
« Reply #30 - Posted 2008-10-26 19:54:45 »

I was right, now it works:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
/**
 * Try to find a mixer that both supports this line and supports
 * as much line as possible
 */

private static final Mixer getBestFittedMixer(DataLine.Info info){
    Mixer currentMixer=null;
    Mixer.Info[] mi=AudioSystem.getMixerInfo();
    Mixer bestMixer=null;
    for(int i=0;i<mi.length;i++)
        {currentMixer=AudioSystem.getMixer(mi[i]);
         if(currentMixer.isLineSupported(info))
             if(bestMixer==null||bestMixer.getMaxLines(info)<currentMixer.getMaxLines(info))
                 bestMixer=currentMixer;                        
        }
    //The best mixer cannot be null as AudioSystem.isLineSupported returned true
    return(bestMixer);
}


I'm now improving the gain system. I will submit my modifications on the SVN repository of TUER, I encourage you to watch the source code. As there was no license, I had to put one (to avoid some legal problems and because TUER is considered as a 100% open source project), I hope it is not problematic, sorry.

Offline tom
« Reply #31 - Posted 2008-10-31 12:15:57 »

I've tried to use EasyOgg but found it buggy when playing the same clip more than once. Test it by playing 10 clips in a loop:
1  
2  
3  
for (int i=0; i<10; i++) {
  ogg.play();
}

I get a bunch of the following exception:
1  
2  
3  
4  
java.lang.NullPointerException
        at org.newdawn.easyogg.OggClip.stop(OggClip.java:301)
        at org.newdawn.easyogg.OggClip.play(OggClip.java:228)
        ...


I've looked at the code and I think it is caused by threading bugs. A new thread is started every time play is invoked. This is done without waiting for the previous thread to stop. This causes bugs as the threads change the same shared member variables. I'll try to fix this if/when I get the time and send the changes to kev. Until then I've made a wrapper that creates a new OggClip every time play is invoked. That way OggClip.play() is never invoked more than once. Here it is:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
package org.newdawn.easyogg;

import java.io.IOException;
import java.net.URL;

/**
 * Wraps an OggClip to avoid the threading bugs in OggClip. The wrapper can be
 * played more than once at a time without problem.
 */

public class OggClipWrapper {
   
    private OggClip clip;
    private URL resource;
    private float gain;
    private boolean isLooping = false;
   
    public OggClipWrapper(URL resource, float gain) {
        this.resource = resource;
        this.gain = gain;
    }
   
    public void play() {
        if (clip != null && isLooping) {
            clip.stop();
        }
        isLooping = false;

        try {
            clip = new OggClip(resource.openStream());
            clip.setGain(gain);
            clip.play();
        } catch (IOException e) {
            e.printStackTrace();
            clip = null;
        }
    }
   
    public void stop() {
        if (clip != null) {
            isLooping = false;
            clip.stop();
            clip = null;
        }
    }
   
    public void loop() {
        if (clip != null && isLooping) {
            clip.stop();
        }        
       
        try {
            clip = new OggClip(resource.openStream());
            clip.setGain(gain);
            clip.loop();
            isLooping = true;
        } catch (IOException e) {
            e.printStackTrace();
            clip = null;
        }
    }
   
    public void pause() {
        if (clip != null) {
            clip.pause();
        }
    }
   
    public void resume() {
        if (clip != null) {
            clip.resume();
        }
    }
}

This has the added "benifit" of being able to play the same clip more than once at the same time.

Offline gouessej
« Reply #32 - Posted 2008-10-31 12:28:03 »

On my view, having to create several clips to play the same sound several times even though one of the clips is still been played is not a bug but what happens when you play a clip that is still been played is a bug.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline tom
« Reply #33 - Posted 2008-10-31 13:27:11 »

I think it is a bug. If you want to play the same OggClip twice you have to do something like this:
1  
2  
3  
4  
5  
ogg.stop();
while(!ogg.stopped()) {
  Thread.yield()
}
ogg.play();


...not how the api was inteded to be used.

Offline gouessej
« Reply #34 - Posted 2008-11-01 12:45:51 »

I think it is a bug. If you want to play the same OggClip twice you have to do something like this:
1  
2  
3  
4  
5  
ogg.stop();
while(!ogg.stopped()) {
  Thread.yield()
}
ogg.play();


...not how the api was inteded to be used.
Thanks. I will update my source code to handle this case, you're right.

Offline gouessej
« Reply #35 - Posted 2008-11-01 17:26:23 »

There is another bug. When you play a sound whose length is less than the buffer size, it doesn't work.

Offline gouessej
« Reply #36 - Posted 2008-11-03 21:04:01 »

I think I'm going to rewrite something to play ogg samples because EasyOgg samples are streamed at real time whereas I would like to load data prior to playback in order to get better performance, more accurate control (better stop mechanism) and no more need of creating lots of threads. Maybe Pulpcore has a better support of ogg files.

Offline tom
« Reply #37 - Posted 2008-11-04 12:57:02 »

I thought about trying to fix the stopping bug, but found out that it would be easier to start from scratch. One of the problems is that the constructor takes an InputStream. I only need it to take an URL which makes things much easier. I can just open up a new stream from the URL instead of synchronizing it with the previous player thread. It is trivial to add a constructor that takes a byte array containing the ogg file. So it is easily possible to extend it so the sound can be streamed from memory, without passing an InputStream to the constructor. Also if you use an URL the whole ogg file will not be loaded into memory like EasyOgg does.

I've got a working version that has almost the same api as EasyOgg. I've replaced the setGain with setVolume that converts the normalised value between 0-1 to a gain dB using the following formula:
1  
float gain = (float) (Math.log(volume) / Math.log(10.0) * 20.0);

No need for a -1 "default" gain value.

I also use OggInputStream to decode the file. It is easier to use and it has some bug fixes in it. It will play sounds whose length is less than the buffer size.

Also added a fade duration that will fade the sound in and out on pause, resume and stop. I use it because it sounds better, but I assume it can also be used to remove clicking.

I plan to release the code, when it is a bit more polished.

Offline zammbi

JGO Coder


Medals: 4



« Reply #38 - Posted 2008-11-04 13:50:38 »

I still had a lot problems when I used easyOgg myself, it just never really worked well for me.
So wouldn't mind seeing what you come up with tom.

Current project - Rename and Sort
Offline gouessej
« Reply #39 - Posted 2008-11-04 15:22:47 »

I still had a lot problems when I used easyOgg myself, it just never really worked well for me.
So wouldn't mind seeing what you come up with tom.
Don't forget that EasyOgg calls the method drain(), it is a blocking method  Sad It is not well fitted for gaming. I think EasyOgg is excellent for a small media player but not for a true game.

I thought about trying to fix the stopping bug
I fixed this bug but I use a different approach, I use sounds (Clip) that are loaded prior to playback to avoid input/output during the game. I will submit my modifications on my SVN repository in some days. Nevertheless, I have modified a little bit the API to fit into my needs and I've been writing a sound manager to be able to play several sounds together but by avoiding any blocking call and by minimizing the use of sound resource, it is very important to prevent the playback from decreasing the frame rate.

About licensing, as EasyOgg is inspired of JOrbisPlayer (under GPL license), TUER is under GPL license and my classes reuses a piece of code written by Vincent Stahl extracted from d3caster (under GPL license), obviously my classes are under GPL license, I hope it is not a problem (don't forget the viral clause).

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline gouessej
« Reply #40 - Posted 2008-11-05 08:55:09 »

I also use OggInputStream to decode the file.
OggInputStream depends on LWJGL as far as I know, it is a bad idea for projects that use JOGG and JORBIS to avoid using JOAL that is buggy under Linux.

Nevertheless, there is a version of OggInputStream for JORBIS here:
http://home.halden.net/tombr/ogg/OggInputStream.java
I'm going to use this one if possible.

Offline tom
« Reply #41 - Posted 2008-11-05 09:47:14 »

OggInputStream depends on LWJGL as far as I know, it is a bad idea for projects that use JOGG and JORBIS to avoid using JOAL that is buggy under Linux.

Nevertheless, there is a version of OggInputStream for JORBIS here:
http://home.halden.net/tombr/ogg/OggInputStream.java
I'm going to use this one if possible.

That was actually the OggInputStream I was referring to (I wrote it btw) Wink Did not know there were another OggInputStream around.

Anyway, I've attached my new OggClip.

edit: I've added fallback support for loading to JavaSound, so it is possible to send in wav files and it should work.

Offline Matzon

JGO Knight


Medals: 19
Projects: 1


I'm gonna wring your pants!


« Reply #42 - Posted 2008-11-05 11:03:00 »

fwiw, lwjgl uses openal-soft, which should work fine under linux ?

Offline gouessej
« Reply #43 - Posted 2008-11-05 19:49:48 »

That was actually the OggInputStream I was referring to (I wrote it btw) Wink Did not know there were another OggInputStream around.

Anyway, I've attached my new OggClip.

edit: I've added fallback support for loading to JavaSound, so it is possible to send in wav files and it should work.
Fine but you still use some threads.

Offline gouessej
« Reply #44 - Posted 2008-11-05 20:23:10 »

Please find my source code below. Nevertheless, I have not tested it, I'm going to do it:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
/*This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation, version 2
  of the License.
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA 02111-1307, USA.
*/

package sound;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;

/**
 * This class handles an OGG sound sample whose data are loaded prior
 * to playback to improve the performance (instead of streaming at real time).
 * The only drawback of this method is not to support samples with variable rates.
 * Moreover, the use is split in several steps to handle the resource carefully.
 * It is well fitted for programs that require a fine control on sounds, for example
 * games using lots of noises. It is possible to prepare a sample without
 * opening it in order to avoid busying a line uselessly. On the other hand, it is
 * possible to close a sample for the same reason. I do not try to reopen the
 * underlying clip because it is highly probable to fail and it is more efficient to
 * close the previous line cleanly and then to get a fresh line by taking into
 * account the modifications of the context that might have happened between the
 * latest opening and the latest closure (for example, the mixer used previously might
 * have become unavailable).
 * @author Julien Gouesse
 *
 */

public final class Sample{
   
   
    private Clip clip;
   
    private byte[] uncompressedDataArray;
   
    private AudioFormat audioFormat;

   
    Sample(InputStream inputStream)throws IllegalArgumentException{
        Map.Entry<byte[],int[]> result=loadOgg(inputStream);
        int rate=result.getValue()[0];
        int channels=result.getValue()[1];
        uncompressedDataArray=result.getKey();      
        audioFormat=new AudioFormat(rate,16,channels,true,false);
        if(uncompressedDataArray==null)
            throw new IllegalArgumentException("Sound sample not supported, data loading failed");      
    }
   
    Sample(File file) throws IllegalArgumentException,FileNotFoundException{
        this(new BufferedInputStream(new FileInputStream(file)));
    }
   
    Sample(URL url) throws IllegalArgumentException,FileNotFoundException,URISyntaxException{
        this(new BufferedInputStream(new FileInputStream(new File(url.toURI()))));
    }
   
    Sample(Sample sample){
        uncompressedDataArray=sample.uncompressedDataArray;
        audioFormat=sample.audioFormat;
        clip=null;
    }
   
    /**
     * Open a sample to prepare it to be played.
     * Do it prior to play the sample.
     * @throws IllegalArgumentException
     */

    private void open()throws IllegalArgumentException{
        if(clip!=null&&clip.isOpen())
            throw new UnsupportedOperationException("Impossible to open an already opened sample");
        //Now we are sure that the clip is null or closed
        DataLine.Info info = new DataLine.Info(Clip.class,audioFormat,AudioSystem.NOT_SPECIFIED);      
        if(AudioSystem.isLineSupported(info))
            {Mixer mixer=getBestFittedMixer(info);
             try{clip=(Clip)mixer.getLine(info);
                 clip.open(audioFormat,uncompressedDataArray,0,uncompressedDataArray.length);
                }
             catch(LineUnavailableException lue)
             {throw new IllegalArgumentException("Sound sample not supported",lue);}
            }
        else
            throw new IllegalArgumentException("Sound sample not supported, no line supported");
    }
   
    /**
     * Load an OGG file
     * @param inputStream
     * @return data, rate and channels
     */

    private static final Map.Entry<byte[],int[]> loadOgg(InputStream inputStream){
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        byteOutputStream.reset();
        byte[] tmpBuffer=new byte[10240*4];
        OggInputStream oggInputStream=new OggInputStream(inputStream);
        boolean done = false;
        int bytesRead;
        while(!done)
            {try{bytesRead=oggInputStream.read(tmpBuffer,0,tmpBuffer.length);}
             catch(IOException ioe)
             {ioe.printStackTrace();
              bytesRead=0;
             }
             byteOutputStream.write(tmpBuffer,0,bytesRead);
             done=(bytesRead!=tmpBuffer.length||bytesRead<0);
            }
        byte[] uncompressedData=byteOutputStream.toByteArray();
        return(new SimpleEntry<byte[],int[]>(uncompressedData,new int[]{oggInputStream.getRate(),oggInputStream.getFormat()}));
    }
   
    /**
     * Reopen a closed sample
     * Notice that a new line might be used
     * @return true if the sample is already usable or if the operation has been successful
     *         false if the operation has failed
     */

    public final boolean reopen(){
        boolean success=true;
        if(clip!=null&&!clip.isOpen())
            try{open();}
            catch(IllegalArgumentException iae)
            {success=false;}
        return(success);
    }
   
   
   
    /**
     * Release the line and the native resources
     * NB: On Mac, the JVM 1.5 freezes after this call
     */

    public final void close(){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to close a closed sample or a never-opened sample");
        try{clip.close();}
        catch(SecurityException se)
        {se.printStackTrace();}
    }
   
    /**
     * Play the sample once from the beginning
     */

    public final void play(){
        loop(1);
    }
   
    /**
     * Pause the sample
     */

    public final void pause(){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to pause a closed sample");
        if(clip.isRunning())
            clip.stop();                              
    }
   
    /**
     * Resume a paused sample from the paused frame and play it count times
     * Do nothing if the sample was not paused
     * @param count
     */

    public void resume(int count){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to resume a closed sample");
        if(!clip.isRunning())
            clip.loop(count);          
    }
   
    /**
     * Play it indefinitely from the beginning
     */

    public final void loop(){
        loop(Clip.LOOP_CONTINUOUSLY);
    }
   
    /**
     * Play it count times from the beginning
     * @param count
     */

    public final void loop(int count){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to play a closed sample");
        if(clip.isRunning())
            stop();    
        clip.loop(count);
    }
   
    /**
     * Stop the sample and rewind it
     */

    public final void stop(){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to stop a closed sample");
        clip.stop();
        clip.setFramePosition(0);
    }
   
    /**
     * Try to find a mixer that both supports this line and supports
     * as much line as possible
     */

    private static final Mixer getBestFittedMixer(DataLine.Info info){
        Mixer currentMixer=null;
        Mixer.Info[] mi=AudioSystem.getMixerInfo();
        Mixer bestMixer=null;
        for(int i=0;i<mi.length;i++)
            {currentMixer=AudioSystem.getMixer(mi[i]);
             if(currentMixer.isLineSupported(info))
                 if(bestMixer==null||bestMixer.getMaxLines(info)<currentMixer.getMaxLines(info))
                     bestMixer=currentMixer;                        
            }
        //The best mixer cannot be null as AudioSystem.isLineSupported returned true
        return(bestMixer);
    }
}


I will add the gain and the balance control later, it doesn't require a lot of time.

Offline zammbi

JGO Coder


Medals: 4



« Reply #45 - Posted 2008-11-07 10:02:08 »

That was actually the OggInputStream I was referring to (I wrote it btw) Wink Did not know there were another OggInputStream around.

Anyway, I've attached my new OggClip.

edit: I've added fallback support for loading to JavaSound, so it is possible to send in wav files and it should work.

I was trying it out, but I can't seem to stop the music in my game. The same clip works fine when using your test case.
What I'm doing is stopping the music then closing the window and creating another window, but seems the music just keeps on playing.
I even tried turning fade off and adding a few second wait. I can't see what is wrong... Also makes a clicking noise for a few seconds.
Also be great if there was a setdefaultvolume method.
Keep up the good work.

Edit: I think it might be to do with that I'm using another thread to stop it. Any solutions to solve this?

Current project - Rename and Sort
Offline gouessej
« Reply #46 - Posted 2008-11-07 10:23:16 »

Edit: I think it might be to do with that I'm using another thread to stop it. Any solutions to solve this?
Use a shutdown hook like TUER (cf. connection.GameServiceProvider.java).

Offline zammbi

JGO Coder


Medals: 4



« Reply #47 - Posted 2008-11-07 12:59:19 »

Seems isStopped doesn't return the correct value after something has finished playing.
Also line 280, variable "OggInputStream oggIn = new OggInputStream(in)" in OggClip class is never closed.

Current project - Rename and Sort
Offline tom
« Reply #48 - Posted 2008-11-07 14:35:30 »

Seems isStopped doesn't return the correct value after something has finished playing.
Also line 280, variable "OggInputStream oggIn = new OggInputStream(in)" in OggClip class is never closed.

This should be fixed in the attached version.

Quote from: zammbi
I was trying it out, but I can't seem to stop the music in my game. The same clip works fine when using your test case.
What I'm doing is stopping the music then closing the window and creating another window, but seems the music just keeps on playing.
I even tried turning fade off and adding a few second wait. I can't see what is wrong... Also makes a clicking noise for a few seconds.
Sorry, but I can't reproduce, and I have no idee what is wrong. In the attached file it tests stopping the clip from a separate thread. Seems to work here.

Quote from: zammbi
Also be great if there was a setdefaultvolume method.
What should it do? The default volume is 1 which will play the clip without changing the gain. A volume of 0 will mute. Volume larger than 1 is allowed and will increase the sound.

Offline tom
« Reply #49 - Posted 2008-11-07 14:46:13 »

Fine but you still use some threads.
Yes, and I agree that starting a new tread every time a sound is played is not a good practice. Also agree that streaming and decoding the ogg in real time is not needed when playing clips.

However if you need to play background music then it's another mather. And for this EasyOgg should do the job as you probably don't end up playing the music twice at the same time.

Performance is not important in the project I'm using this for. I just a need an easy way of playing clips. And it seems to be working great so I'm happy.

Offline zammbi

JGO Coder


Medals: 4



« Reply #50 - Posted 2008-11-07 15:12:45 »

This should be fixed in the attached version.
Thanks, though you still don't close the file, when your done.

Sorry, but I can't reproduce, and I have no idee what is wrong. In the attached file it tests stopping the clip from a separate thread. Seems to work here.
You example does work for me too, so It isn't just a thread problem.
Heres a small test case.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
        ogg.loop();
        JFrame frame = new JFrame();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.addKeyListener(new KeyAdapter(){
         @Override
         public void keyPressed(final KeyEvent evt) {
                   try {
                       Thread.sleep(3000);
                       System.out.println("stop()");
                       System.out.println("is clip stopped1 " + ogg.isStopped());
                       ogg.stop();
                       System.out.println("is clip stopped2 " + ogg.isStopped());
                       while (!ogg.isStopped()) {
                           System.out.println("clip not stopped");
                       }
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
      });


What should it do? The default volume is 1 which will play the clip without changing the gain. A volume of 0 will mute. Volume larger than 1 is allowed and will increase the sound.

Sorry didn't know 1 was default.

Current project - Rename and Sort
Offline tom
« Reply #51 - Posted 2008-11-07 16:52:37 »

Thanks for the test case. Managed to reproduce fhe bug. It is now fixed. Se attachment.

Quote
Thanks, though you still don't close the file, when your done.
What do you mean? java.io.File can not be closed!

I do close the stream if that is what you mean.

Offline zammbi

JGO Coder


Medals: 4



« Reply #52 - Posted 2008-11-08 09:39:47 »

Quote
What do you mean? java.io.File can not be closed!

I do close the stream if that is what you mean.

Oh ok, just that FindBugs was complaining about it.

So far everything seems to be going well. I do seem to get some clicking sounds on my music when using fade while playing another sound.

Current project - Rename and Sort
Offline gouessej
« Reply #53 - Posted 2008-11-10 12:31:37 »

I don't know if someone might be interested in what I have written in order to play ogg sounds... I've tested it and it works fine, it is very accurate, I only have some problems when I resume a loop. I'm going to commit my modifications on my SVN repository.

Offline gouessej
« Reply #54 - Posted 2008-11-10 15:07:06 »

My source code is below, the method void resume(int count) doesn't work, I tried to use setLoopPoints, flush, start, etc... without success. If you have an idea, please let me know. You need the class OggInputStream (I gave the pointer to download it in a previous post above) to compile and use my class. Don't forget to open a sample before using it.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
/*This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation, version 2
  of the License.
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA 02111-1307, USA.
*/

package sound;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;

/**
 * This class handles an OGG sound sample whose data are loaded prior
 * to playback to improve the performance (instead of streaming at real time).
 * The only drawback of this method is not to support samples with variable rates.
 * Moreover, the use is split in several steps to handle the resource carefully.
 * It is well fitted for programs that require a fine control on sounds, for example
 * games using lots of noises. It is possible to prepare a sample without
 * opening it in order to avoid busying a line uselessly. On the other hand, it is
 * possible to close a sample for the same reason. I do not try to reopen the
 * underlying clip because it is highly probable to fail and it is more efficient to
 * close the previous line cleanly and then to get a fresh line by taking into
 * account the modifications of the context that might have happened between the
 * latest opening and the latest closure (for example, the mixer used previously might
 * have become unavailable).
 * @author Julien Gouesse
 *
 */

public final class Sample{
   
   
    private Clip clip;
   
    private byte[] uncompressedDataArray;
   
    private AudioFormat audioFormat;

   
    /**
     *
     * @param inputStream
     * @throws IllegalArgumentException
     */

    public Sample(InputStream inputStream)throws IllegalArgumentException{
        //pausedFramePosition=0;
        Map.Entry<byte[],int[]> result=loadOgg(inputStream);
        int rate=result.getValue()[0];
        int channels=result.getValue()[1];
        uncompressedDataArray=result.getKey();      
        audioFormat=new AudioFormat(rate,16,channels,true,false);
        if(uncompressedDataArray==null)
            throw new IllegalArgumentException("Sound sample not supported, data loading failed");      
    }
   
    public Sample(File file) throws IllegalArgumentException,FileNotFoundException{
        this(new BufferedInputStream(new FileInputStream(file)));
    }
   
    public Sample(URL url) throws IllegalArgumentException,FileNotFoundException,URISyntaxException{
        this(new BufferedInputStream(new FileInputStream(new File(url.toURI()))));
    }
   
    public Sample(Sample sample){
        uncompressedDataArray=sample.uncompressedDataArray;
        audioFormat=sample.audioFormat;
        clip=null;
    }
   
    /**
     * Open a sample to prepare it to be played.
     * Do it prior to play the sample.
     * @throws IllegalArgumentException
     */

    public final void open()throws IllegalArgumentException{
        if(clip!=null&&clip.isOpen())
            throw new UnsupportedOperationException("Impossible to open an already opened sample");
        //Now we are sure that the clip is null or closed
        DataLine.Info info = new DataLine.Info(Clip.class,audioFormat,AudioSystem.NOT_SPECIFIED);      
        if(AudioSystem.isLineSupported(info))
            {Mixer mixer=getBestFittedMixer(info);
             try{clip=(Clip)mixer.getLine(info);
                 clip.open(audioFormat,uncompressedDataArray,0,uncompressedDataArray.length);
                }
             catch(LineUnavailableException lue)
             {throw new IllegalArgumentException("Sound sample not supported",lue);}
            }
        else
            throw new IllegalArgumentException("Sound sample not supported, no line supported");
    }
   
    /**
     * Load an OGG file
     * @param inputStream
     * @return data, rate and channels
     */

    private static final Map.Entry<byte[],int[]> loadOgg(InputStream inputStream){
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        byteOutputStream.reset();
        byte[] tmpBuffer=new byte[10240*4];
        OggInputStream oggInputStream=new OggInputStream(inputStream);
        boolean done = false;
        int bytesRead;
        while(!done)
            {try{bytesRead=oggInputStream.read(tmpBuffer,0,tmpBuffer.length);}
             catch(IOException ioe)
             {ioe.printStackTrace();
              bytesRead=0;
             }
             byteOutputStream.write(tmpBuffer,0,bytesRead);
             done=(bytesRead!=tmpBuffer.length||bytesRead<0);
            }
        byte[] uncompressedData=byteOutputStream.toByteArray();
        return(new SimpleEntry<byte[],int[]>(uncompressedData,new int[]{oggInputStream.getRate(),oggInputStream.getFormat()}));
    }
   
    /**
     * Reopen a closed sample
     * Notice that a new line might be used
     * @return true if the sample is already usable or if the operation has been successful
     *         false if the operation has failed
     */

    public final boolean reopen(){
        boolean success=true;
        if(clip!=null&&!clip.isOpen())
            try{open();}
            catch(IllegalArgumentException iae)
            {success=false;}
        return(success);
    }
   
   
   
    /**
     * Release the line and the native resources
     * NB: On Mac, the JVM 1.5 freezes after this call
     */

    public final void close(){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to close a closed sample or a never-opened sample");
        try{clip.close();}
        catch(SecurityException se)
        {se.printStackTrace();}
    }
   
    /**
     * Play the sample once from the beginning
     */

    public final void play(){
        loop(1);
    }
   
    /**
     * Pause the sample
     */

    public final void pause(){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to pause a closed sample");
        if(clip.isRunning())
            clip.stop();
    }
   
    /**
     * Resume a paused sample from the paused frame and play it count times
     * Do nothing if the sample was not paused
     * @param count
     */

    public void resume(int count){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to resume a closed sample");        
        if(!clip.isRunning())
            {//FIXME: the line below should not be used, that's the only way I've found
             //to repair this class when resuming a loop
             //clip.setFramePosition(0);
             clip.loop(count);
            }      
    }
   
    /**
     * Play it indefinitely from the beginning
     */

    public final void loop(){
        loop(Clip.LOOP_CONTINUOUSLY);
    }
   
    /**
     * Play it count times from the beginning
     * @param count
     */

    public final void loop(int count){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to play a closed sample");
        if(clip.isRunning())
            stop();    
        clip.loop(count);
    }
   
    /**
     * Stop the sample and rewind it
     */

    public final void stop(){
        if((clip!=null&&!clip.isOpen())||clip==null)
            throw new UnsupportedOperationException("Impossible to stop a closed sample");
        clip.stop();
        clip.setFramePosition(0);
    }
   
    public final boolean isRunning(){
        return(clip!=null&&clip.isOpen()&&clip.isRunning());
    }
   
    /**
     * Try to find a mixer that both supports this line and supports
     * as much line as possible
     */

    private static final Mixer getBestFittedMixer(DataLine.Info info){
        Mixer currentMixer=null;
        Mixer.Info[] mi=AudioSystem.getMixerInfo();
        Mixer bestMixer=null;
        for(int i=0;i<mi.length;i++)
            {currentMixer=AudioSystem.getMixer(mi[i]);
             if(currentMixer.isLineSupported(info))
                 if(bestMixer==null||bestMixer.getMaxLines(info)<currentMixer.getMaxLines(info))
                     bestMixer=currentMixer;                        
            }
        //The best mixer cannot be null as AudioSystem.isLineSupported returned true
        return(bestMixer);
    }
}

Offline zammbi

JGO Coder


Medals: 4



« Reply #55 - Posted 2009-02-28 03:57:25 »

Tom you still working on your OggClip?

Seems my users are complaining that the walking sound its making my game unplayable.
I have noticed that it does use a lot of cpu to play short repeated sounds.
Like:
1  
2  
3  
4  
         
if(ogg.isStopped()){
   ogg.play();
}


Its great for music just not repeating short sounds.

I using loop and then pausing/resuming seems a little better but looping has to play the sound a few times. It will keep playing for a few times after I sent the pause.

Are you able to look into this issue?

gouessej I would try your code but you said in your comments that it freezes on mac Java 1.5.

Current project - Rename and Sort
Offline tom
« Reply #56 - Posted 2009-02-28 22:28:02 »

Haven't changed it since last time I posted. I have to admit that playing a sound is a fairly heavy operation. Since it creates a new thread. You could modify the code to add a playOnceThenPause method. I don't have the time to add it. I also think it is too specialized for it to be a valuable addition to the class. However I will help you if you want to do it yourself. You have to set a flag that will pause the playback after playing it once. At line 423 you have to check for this flag and set the paused flag to true.

I've discovered another problem with OggClip when I used it in my application. Streaming more than one sound with JavaSound will cause stuttering. It's because the JavaSound implementation is crap/broken.

Offline i30817

Junior Devvie





« Reply #57 - Posted 2009-03-03 21:32:16 »

How about doing the obvious thing and using a cachedThreadExecutor instead of spawning a thread whenever you want?
Offline tom
« Reply #58 - Posted 2009-03-03 21:58:51 »

That would be to easy  Smiley

Offline zammbi

JGO Coder


Medals: 4



« Reply #59 - Posted 2009-03-05 10:23:42 »

Thanks for the help, I did what you suggested, but saw no decrease in cpu myself.

Current project - Rename and Sort
Pages: 1 [2] 3
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CopyableCougar4 (16 views)
2014-12-28 02:10:29

BurntPizza (17 views)
2014-12-27 22:38:51

Mr.CodeIt (13 views)
2014-12-27 04:03:04

TheDudeFromCI (17 views)
2014-12-27 02:14:49

Mr.CodeIt (25 views)
2014-12-23 03:34:11

rwatson462 (56 views)
2014-12-15 09:26:44

Mr.CodeIt (46 views)
2014-12-14 19:50:38

BurntPizza (92 views)
2014-12-09 22:41:13

BurntPizza (113 views)
2014-12-08 04:46:31

JscottyBieshaar (86 views)
2014-12-05 12:39:02
How do I start Java Game Development?
by gouessej
2014-12-27 19:41:21

Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!