简体   繁体   中英

Error playing music in Java program

Ok, so today I finally decided to ask what the issue was with my Java program after various attempts to fix it. If you didn't read the title, here is my issue: I'm trying to play music in a program, but it returns an error.

So first, I have to put the most important part; the class

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Runawaytrain {
    public void play() { 
        try { 
            AudioInputStream in = AudioSystem.getAudioInputStream(new File("hard1.wav"));
            Clip clip = AudioSystem.getClip(); 
            clip.open(in); 
            clip.start(); 
            Thread.sleep(clip.getMicrosecondLength()); 
        } catch (Exception e) { 
            e.printStackTrace();
        } 
    }
    public static void main(String[] args){
        new Runawaytrain().play();
    }
}

This program I actually used as a test, since the music I was using in a game I'm co-creating wouldn't play. So when I made this program, I got the same stack trace:

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
    at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1189)
    at krap2.Runawaytrain.play(Runawaytrain.java:12)
    at krap2.Runawaytrain.main(Runawaytrain.java:22)

The file hard1.wav is included in my project directory. For some reason, it won't play however, and keeps returning that stack trace.

But I found something pretty odd about my program; when I use music from a URL, it works. So I tried inserting a URL using the file:// protocol, but still no luck.

So anyway, to finish this off, I'll put some info that may help in answering the question:

• OS: Mac

• JVM installed: 1.8.0

• Music source: Originally an MP3 file, converted through VLC into a .wav format

Thanks

我很确定您在制作新的File()时需要放置文件的整个系统路径(因此,在Windows上,它将是“ Users / username /.../ hard1.wav”或其他内容)苹果机)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM