How to play audio in Java Application

前端 未结 4 1995
悲&欢浪女
悲&欢浪女 2020-12-07 05:40

I\'m making a java application and I need to play audio. I\'m playing mainly small sound files of my cannon firing (its a cannon shooting game) and the projectiles exploding

相关标签:
4条回答
  • 2020-12-07 06:04

    The problem with this is that my entire program stops until the sound file is finished, or at least nearly finished.

    This screams a threading issue. Have you tried playing the sound in a background thread? By the way, is this a Swing program? If so, use a SwingWorker to play the sound. There are many reasons for this, but one primary reason is that it's easy to track the state of the thread via the PropertyChangeListener support built in to SwingWorker.

    0 讨论(0)
  • 2020-12-07 06:07

    You should create a thread that handles the audio playback. But make sure that it is able to mix in sounds, so two shots that happen after each other can get their sounds played at the correct time, without waiting for the prior sound to finish. There should be Frameworks out there that do the mixing for you.

    A good starting point is: http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html

    0 讨论(0)
  • 2020-12-07 06:18

    I guess you should run your playSound method in a background thread as mentioned in the doc here

    "you'll probably want to invoke this playback loop in a separate thread from the rest of the application program, so that your program doesn't appear to freeze when playing a long sound"

    Maybe by doing something like

    // shared executor
    ExecutorService soundExecutor = ...; //Executors.newSingleThreadExecutor();
    ...
    final File soundFile = ...;
    soundExecutor.submit(new Runnable(){
       public void run(){
            SoundUtils.playSoundFile(soundFile);
       }
    });
    
    0 讨论(0)
  • 2020-12-07 06:30

    For the first method you have to create another thread for audio.

    For example like this:

    new Thread(
                new Runnable() {
                    public void run() {
                        try {
                            // PLAY AUDIO CODE
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
    

    Of course you have to make sure that previous sound isn't still playing.

    0 讨论(0)
提交回复
热议问题