简体   繁体   English

在Java程序中播放音乐时出错

[英]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. 好的,所以今天我终于决定在尝试各种Java程序后再问问题。 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. 文件hard1.wav包含在我的项目目录中。 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. 当我使用URL中的音乐时,它可以工作。 So I tried inserting a URL using the file:// protocol, but still no luck. 因此,我尝试使用file://协议插入URL,但还是没有运气。

So anyway, to finish this off, I'll put some info that may help in answering the question: 因此,无论如何,为了完成此任务,我将提供一些有助于回答问题的信息:

• OS: Mac •操作系统:Mac

• JVM installed: 1.8.0 •已安装JVM:1.8.0

• Music source: Originally an MP3 file, converted through VLC into a .wav format •音乐源:最初是MP3文件,通过VLC转换为.wav格式

Thanks 谢谢

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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