ubuntu 通过剪辑和AudioInputStream播放Java声音不起作用

qjp7pelc  于 6个月前  发布在  Java
关注(0)|答案(2)|浏览(63)

这是一个从Java声音信息页面稍微修改的例子。https://stackoverflow.com/tags/javasound/info不幸的是,它只播放一次声音,但意图是两次。

import java.io.File;
import javax.sound.sampled.*;

public class TestNoise {
    public static void main(String[] args) throws Exception {
        File f = new File("/home/brian/drip.wav");
        AudioInputStream ais = AudioSystem.getAudioInputStream(f);

        AudioFormat af = ais.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, af);
        Clip clip = (Clip)AudioSystem.getLine(info);

        clip.open(ais);
        clip.start();    // heard this
        Java.killTime(); 
        clip.start();    // NOT HEARD
        Java.killTime();
    }
}

字符串

**编辑:要了解答案,请查看Wanderlust提供的链接,或者按照他的答案下面的评论中所说的去做。

h79rfbju

h79rfbju1#

这个奇妙的API对我很有效:

import javax.sound.sampled.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

/**
 * Handles playing, stopping, and looping of sounds for the game.
 *
 * @author Langdon Staab
 * @author Tyler Tomas
 */
public class Sound {
    Clip clip;

    @SuppressWarnings("CallToPrintStackTrace")
    public Sound(String filename) {
        try (InputStream in = getClass().getResourceAsStream(filename)) {
            assert in != null;
            InputStream bufferedIn = new BufferedInputStream(in);
            try (AudioInputStream audioIn = AudioSystem.getAudioInputStream(bufferedIn)) {
                clip = AudioSystem.getClip();
                clip.open(audioIn);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException("Sound: Malformed URL: \n" + e);
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
            throw new RuntimeException("Sound: Unsupported Audio File: \n" + e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Sound: Input/Output Error: \n" + e);
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            throw new RuntimeException("Sound: Line Unavailable Exception Error: \n" + e);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // play, stop, loop the sound clip
    }

    public void play() {
        clip.setFramePosition(0);  // Must always rewind!
        clip.start();
    }

    public void loop() {
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    }

    public void stop() {
        clip.stop();
    }

    public boolean isPlaying() {
        //return false;
        return clip.getFrameLength() > clip.getFramePosition();
    }
}

字符串

j0pj023g

j0pj023g2#

第二次播放此片段时,您必须调用

clip.start();
clip.stop();

字符串
因为在第二次调用clip.start()之后,它试图从it stopped previously的位置播放文件。

相关问题