2
import javax.sound.sampled.*;
import java.io.File;
public class PlayAudio{
public static void main(String args[])throws Exception{

    File wavFile = new File("C:\\Users\\User\\Desktop\\Wate.wav");
    AudioInputStream ais = AudioSystem.getAudioInputStream(wavFile);
    Clip clip=AudioSystem.getClip();
    clip.open(ais);
    clip.start();
 }
}

私の質問は: このアプリケーションで音楽が再生されないのはなぜですか? (IDEはエクリプス)

4

1 に答える 1

3

問題は、サウンドクリップを再生する前にメインアプリケーションスレッドが終了することです。Thread.sleepの後に任意のタイムアウトで呼び出すことができますが、再生中にオーディオデータを追跡するclip.start()ための専用を作成することをお勧めします。Thread

public class PlayAudio {

    AudioFormat audioFormat;
    AudioInputStream audioInputStream;
    SourceDataLine sourceDataLine;

    boolean stopPlayback = false;

    public void playAudio(File soundFile) throws UnsupportedAudioFileException,
            IOException, LineUnavailableException {
        audioInputStream = AudioSystem.getAudioInputStream(soundFile);
        audioFormat = audioInputStream.getFormat();
        DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
        sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
        new Thread(new PlayThread()).start();
    }

    public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        new PlayAudio().playAudio(new File("myclip.wav"));
    }

    class PlayThread implements Runnable {
        byte soundBuffer[] = new byte[10000];

        @Override
        public void run() {
            try {
                sourceDataLine.open(audioFormat);
                sourceDataLine.start();
                int cnt;
                while ((cnt = audioInputStream.read(soundBuffer, 0,
                        soundBuffer.length)) != -1 && stopPlayback == false) {
                    if (cnt > 1) {
                        sourceDataLine.write(soundBuffer, 0, cnt);
                    }
                }
                sourceDataLine.drain();
                sourceDataLine.close();
                stopPlayback = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
于 2013-01-13T17:16:30.757 に答える