Java同时播放多个剪辑

时间:2014-01-18 23:14:26

标签: java audio javasound clip

所以我的应用程序应该在每次单击面板时播放WAV文件。但现在的问题是,它在第​​二个播放之前等待第一个完成。我希望能够让他们同时玩。

我放置Thread.sleep(500)的原因是因为如果我不这样做,那么它根本不会播放声音:(

    import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class SoundEffectPlayer extends JFrame {

    /*
     * Jframe stuff
     */
    public SoundEffectPlayer() {
        this.setSize(400, 400);
        this.setTitle("Mouse Clicker");
        this.addMouseListener(new Clicker());


        this.setVisible(true);
    }

    private class Clicker extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            try {
                playSound(1);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    /*
     * Directory of your sound files
     * format is WAV
     */
    private static final String DIRECTORY = "file:///C:/Users/Jessica/Desktop/audio/effects/sound 1.wav";

    /*
     * The volume for sound effects
     */
    public static float soundEffectsVolume = 0.00f;

    /*
     * Loads the sound effect files from cache
     * into the soundEffects array.
     */
    public void playSound(int ID) throws InterruptedException {

        try {
            System.out.println("playing");
            Clip clip;
            URL url = new URL(DIRECTORY);
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
            clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.setFramePosition(0);
            FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
            gainControl.setValue(soundEffectsVolume);

            clip.start();   
            System.out.println("played");
            Thread.sleep(3000);
            System.out.println("closing");

        } catch (MalformedURLException e) {
            System.out.println("Sound effect not found: "+ID);
            e.printStackTrace();
            return;
        } catch (UnsupportedAudioFileException e) {
            System.out.println("Unsupported format for sound: "+ID);
            return;
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }   
    }
    public static void main(String[] args) throws InterruptedException {
        new SoundEffectPlayer();
    }
}

更新:好的,所以我让他们在simeutaneously玩,但我想在Clip完成播放时让线程关闭,而不是让线程等待500ms

我该怎么做?

2 个答案:

答案 0 :(得分:1)

尝试检查此开源音板程序的源代码:DBoard

您对使用MediaPlayer课程特别感兴趣。你可以用

来调用它
(new Thread(new MediaPlayer(PATHTOFILE)).start();

答案 1 :(得分:1)

我总是运行这样的多个声音。我不会产生一个新线程,因为我猜javaSound已经在另一个线程中运行了剪辑。主要"游戏循环"可能会继续做自己的事情。应用程序可以注册侦听器以进行回调或使用getter来查看正在执行的剪辑。

有时,如果我们要制作多媒体或游戏应用程序,那么更容易使用getter。运行游戏循环30-60fps可以为大多数情况提供足够的粒度,我们可以完全控制发生的事情和时间。这个小testapp播放两个wav文件,第一个运行一次,第二个在3秒后启动,第二个循环。

// java -cp ./classes SoundTest1 clip1=sound1.wav clip2=sound2.wav
import java.util.*;
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;

public class SoundTest1 {

    public Clip play(String filename, boolean autostart, float gain) throws Exception {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(filename));
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.setFramePosition(0);

        // values have min/max values, for now don't check for outOfBounds values
        FloatControl gainControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
        gainControl.setValue(gain);

        if(autostart) clip.start();
        return clip;
    }

//**************************************
    public static void main(String[] args) throws Exception {
        Map<String,String> params = parseParams(args);
        SoundTest1 test1 = new SoundTest1();

        Clip clip1 = test1.play(params.get("clip1"), true, -5.0f);
        Clip clip2 = test1.play(params.get("clip2"), false, 5.0f);

        final long duration=20000;
        final int interval=500;
        for(long ts=0; ts<duration; ts+=interval) {
            System.out.println(String.format("clip1=%d/%d, clip2=%d/%d"
                ,clip1.getFramePosition(), clip1.getFrameLength()
                ,clip2.getFramePosition(), clip2.getFrameLength()
            ));
            if (ts>3000 && !clip2.isRunning()) {
                clip2.setFramePosition(0);
                clip2.start();
            }
            if (!clip1.isRunning()) {
                clip1.close();
            }
            Thread.sleep(interval);
        }
    }

    private static Map<String,String> parseParams(String[] args) {
        Map<String,String> params = new HashMap<String,String>();
        for(String arg : args) {
            int delim = arg.indexOf('=');
            if (delim<0) params.put("", arg.trim());
            else if (delim==0) params.put("", arg.substring(1).trim());
            else params.put(arg.substring(0, delim).trim(), arg.substring(delim+1).trim() );
        }
        return params;
    }

}

有关详细信息,请参阅JavaSound documentation