向 Java 程序添加音乐/声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20811728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Music/Sound to Java Programs
提问by JavaDude
I'm making some mini java games and I was wondering how I can add sound/music to my programs. I watched a video on youtube and followed the code provided, however I get the following error: java.io.IOException: could not create audio stream from input stream
我正在制作一些迷你 Java 游戏,我想知道如何将声音/音乐添加到我的程序中。我在 youtube 上观看了一个视频并按照提供的代码进行操作,但是出现以下错误: java.io.IOException:无法从输入流创建音频流
I noticed that others have asked the same question with the same code but the answers were not helpful. Here is the code:
我注意到其他人用相同的代码问了同样的问题,但答案没有帮助。这是代码:
import sun.audio.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Project1
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,200);
frame.setLocationRelativeTo(null);
JButton button = new JButton("Click me");
frame.add(button);
button.addActionListener(new AL());
frame.setVisible(true);
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e){
music();
}
}
public static void music()
{
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try
{
InputStream test = new FileInputStream("C:\Music1.wmv");
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
//MD = BGM.getData();
//loop = new ContinuousAudioDataStream(MD);
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop);
}
}
采纳答案by Andrew Thompson
InputStream test = new FileInputStream("C:\Music1.wmv");
Java Sound has no support for WMV & I've not heard of a Service Provider Interface that will support it. You'll need to convert the sound to an older file type.
Java Sound 不支持 WMV,我也没有听说过支持它的服务提供者接口。您需要将声音转换为较旧的文件类型。
回答by swapnil7
回答by CaptainKnee
Try using:
尝试使用:
InputStream test = new FileInputStream("C:\Music1.au");
Or:
或者:
InputStream test = new FileInputStream("C:\Music1.wav");
Just convert your file to one of these audio files.
只需将您的文件转换为这些音频文件之一。