在特定声音设备 java 上播放声音

Man*_*ore 2 java audio javasound

我正在尝试做一些简单的事情。我想在给定的声音媒体上播放声音,而不是在默认媒体上播放。

这是我最后一次尝试,迭代所有媒体的思想并播放声音。只有默认设备上的媒体播放某些内容。直接播放时,即使默认设备也不工作。

public void testSoundPLayer() throws Exception {
    AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream(Constants.SOUND_ALERT));

    Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
    for(int i = 0; i < mixerInfo.length; i++)
    {
        Mixer.Info info = mixerInfo[i];

        System.out.println(String.format("Name [%s] \n Description [%s]\n\n", info.getName(), info.getDescription()));
        System.out.println(info.getDescription());

        try
        {
            Clip clip = AudioSystem.getClip(info);
            clip.open(inputStream);
            clip.start();
        }
        catch (Throwable t)
        {
            System.out.println(t.toString());
        }
        Thread.sleep(2000L);
    }
}
Run Code Online (Sandbox Code Playgroud)

我愿意使用外部库,甚至更改默认声卡。我只想要一个“不错”的方法来在给定的声卡上播放声音(wav),而不需要依赖于操作系统的方法。

Man*_*ore 5

这是一个耻辱,我犯了一个巨大的错误,我没有重新加载流。这意味着秒播放不起作用。

有一个工作示例。

public void testSoundPLayer() throws Exception {

Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
for(int i = 0; i < mixerInfo.length; i++)
{
    AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream(Constants.SOUND_ALERT));

    Mixer.Info info = mixerInfo[i];

    System.out.println(String.format("Name [%s] \n Description [%s]\n\n", info.getName(), info.getDescription()));
    System.out.println(info.getDescription());

    try
    {
        Clip clip = AudioSystem.getClip(info);
        clip.open(inputStream);
        clip.start();
    }
    catch (Throwable t)
    {
        System.out.println(t.toString());
    }
    Thread.sleep(2000L);
}
Run Code Online (Sandbox Code Playgroud)

}

要检查设备是输入还是输出,请使用以下方法:

// Param for playback (input) device.
Line.Info playbackLine = new Line.Info(SourceDataLine.class);
// Param for capture (output) device.
Line.Info captureLine = new Line.Info(TargetDataLine.class);


private List<Mixer.Info> filterDevices(final Line.Info supportedLine) {
    List<Mixer.Info> result = Lists.newArrayList();

    ArrayList<Mixer.Info> infos = Lists.newArrayList(AudioSystem.getMixerInfo());
    for (Mixer.Info info : infos) {
        Mixer mixer = AudioSystem.getMixer(info);
        if (mixer.isLineSupported(supportedLine)) {
            result.add(info);
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)