AudioInputStream不起作用 [英] AudioInputStream is not working

查看:92
本文介绍了AudioInputStream不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户每次按下按钮时播放.wav声音,但是会引发异常:

I'm trying to play a .wav sound every time the user presses a button, but an exception gets thrown:

Exception in thread "Thread-0" java.lang.IllegalArgumentException: Invalid format
    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.createStream(PulseAudioDataLine.java:142)
    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:99)
    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:283)
    at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:402)
    at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:453)
    at Uber.play(Uber.java:534)
    at Uber$5.run(Uber.java:340)
    at java.lang.Thread.run(Thread.java:724)

代码如下:

//Play Audio File
public void play(String file) throws LineUnavailableException, UnsupportedAudioFileException, IOException
{
    AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(file));
    Clip clip = AudioSystem.getClip();
    clip.open(inputStream);
    clip.start();
}

推荐答案

我设法使其正常运行. 这是我使用的代码.请记住,我只需要播放短的beep.wav声音.较长的声音文件似乎有些麻烦.让我知道它是否对您有用,并且您是否可以使用此代码播放更长的声音.

I managed to get it working. This is the code that I used. Keep in mind that I needed this just to play a short beep.wav sound. It seems to have some trouble with longer sound files. Let me know if it works for you guys and if you manage to play longer sounds with this code.

public void play(String file) throws LineUnavailableException, UnsupportedAudioFileException, IOException
    {

    try 
        {   
            AudioInputStream inputStream = AudioSystem.getAudioInputStream(this.getClass().getResource(file));
            AudioFormat format = inputStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip)AudioSystem.getLine(info);
            clip.open(inputStream);
            clip.start();
        }

    catch (IOException | LineUnavailableException | UnsupportedAudioFileException e1)
        {
            e1.printStackTrace();
        }
    }

这篇关于AudioInputStream不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆