[英]Sound format for a Java-based game
我正在开发一个Java游戏,想要捆绑和播放一些采样的声音效果。 我打算使用标准的javax.sound.sampled功能来播放它们。
哪种格式最适合这类样品? 我正在寻找一种良好的压缩,良好的质量和方便Java编程使用的混合。
质量与尺寸
这里有一些关于MP3与WAV差异的有趣文章。
为何选择MP3和WAV? 这些是我在创建程序时最常见的,因此兼容性从来都不是问题。
我有这个非常有用的java文件,可以为您完成所有事情。 您使用声音文件的路径构造对象,然后使用方法来播放,停止,循环它等。
在此期间,您可以查看这些内容以供参考,尽管它们不那么干净: 如何在Java中播放声音? 。
简单编程
不幸的是,我没有这台计算机上的文件,但这是一个简化版本。 这并不像你希望的那样使用javax.swing,但说实话,我总是喜欢替代方法。
因为这与我在其他计算机上的文件不一样,所以我不能保证兼容MP3。
import sun.audio.*;
import java.io.*;
public class Sound {
private InputStream input;
private AudioStream audio;
public Sound (File fileName)
{
input = new FileInputStream();
audio = new AudioStream(input);
}
public void play()
{
AudioPlayer.player.start(audio);
}
public void stop()
{
AudioPlayer.player.stop(audio);
}
}
实例:
String projectPath = <project directory>; // getting this is another question
Sound helloSound = new Sound(new File(projectPath + "/Sounds"));
现在你可以调用helloSound.play();
每当你想要播放剪辑。
我更喜欢这种方法,因此您不必在每次要播放剪辑时不断地将所有内容设置为流。 这应该有效地与一些声音咬合和模糊,但一定不要过度使用它并占用记忆。 用于常见的声音效果。
简单编程,续
找到一个好的文件播放MP3,就像我上面演示的那样。 我完全忘了把我的东西放在一个单独的线程中,所以这是一个更好的选择。
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3 {
private String filename;
private Player player;
// constructor that takes the name of an MP3 file
public MP3(String filename) {
this.filename = filename;
}
public void close() { if (player != null) player.close(); }
// play the MP3 file to the sound card
public void play() {
try {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();
}
// test client
public static void main(String[] args) {
String filename = args[0];
MP3 mp3 = new MP3(filename);
mp3.play();
// do whatever computation you like, while music plays
int N = 4000;
double sum = 0.0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
sum += Math.sin(i + j);
}
}
System.out.println(sum);
// when the computation is done, stop playing it
mp3.close();
// play from the beginning
mp3 = new MP3(filename);
mp3.play();
}
}
馅饼很简单,对吗? )。
Java支持mp3,mp3格式让您可以选择压缩与质量之间的平衡。
有一个纯java的MP3解码器, http://www.javazoom.net/javalayer/javalayer.html ,它插入javax.sound包。 Sun还发布了一个用于java声音的mp3插件 。
我不是这方面的专家,但Sun的所有教程和示例都使用.au
文件。 似乎是一个保证最低的共同点。 为了提高文件格式的灵活性,您需要使用Java Media Framework之类的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.