Java 音频流不工作,保持 运行 进入错误

Java Audio Streaming isn't Working, keep running into an error

我正在学习这个 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:\Usersando\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

非常感谢您的回复,谢谢

除了你缺少 try/catch 来捕获任何异常之外,你的代码对我有用。

检查 AudioInputStream, AudioSystem, Clip, LineUnavailableException, and finally the UnsupportedAudioFileException. All these classes should be part of the 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);
    }
}