java音频流不工作,继续运行时出错

b5buobof  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(343)

我遵循这个java教程,我遇到了如何播放音频,我按照确切的步骤编写代码,然而,尽管如此,我得到了一个错误消息,我怀疑视频是过时的,因为它只有一个月的历史,所以我不确定是什么问题。
以下是我编写的代码:

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) throws IOException, UnsupportedAudioFileException, LineUnavailableException
    {
        Scanner sc = new Scanner(System.in);

        File file = new File("bababooey.wav");
        AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
        Clip clip = AudioSystem.getClip();
        clip.open(audioStream);

        clip.start();

        String response = sc.next();
    }
}

下面是我一直收到的错误信息:

"C:\Program Files\AdoptOpenJDK\jdk-15.0.1.9-hotspot\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.4\lib\idea_rt.jar=57472:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\1ando\Documents\Programming\Java\Complete Java Tutorial\Audio\out\production\Audio" Main
Exception in thread "main" java.lang.IllegalArgumentException: Audio data < 0
    at java.desktop/com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1086)
    at Main.main(Main.java:12)

Process finished with exit code 1

我非常感谢您的回复,谢谢

chy5wohz

chy5wohz1#

除了缺少try/catch来捕获任何异常之外,您的代码对我很有用。
检查audioinputstream、audiosystem、clip、lineunavailableexception和unsupportedaudiofileexception的导入。所有这些类都应该是javax.sound.sampled包的一部分。进口应:

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

代码可以是这样的:

// Scanner sc = new Scanner(System.in);  // I don't understand why you are using Scanner!
AudioInputStream audioStream = null;
try {
    File file = new File("explosion.wav");
    audioStream = AudioSystem.getAudioInputStream(file);
    Clip clip = AudioSystem.getClip();

    clip.open(audioStream);
    clip.start();
    //String response = sc.next(); // I don't understand why you are using Scanner!
}
catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
    System.err.println(ex);
}
finally {
    try {
        if (audioStream != null) {
            audioStream.close();
        }
    }
    catch (IOException ex) {
        System.err.println(ex);
    }
}

相关问题