我用java做了一个贪吃蛇小游戏,我想看看你贪吃蛇游戏中如何添加的背景音乐(代码)
1个回答
展开全部
import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class Test {
public static void main(String[] args) {
Sound s=new Sound("E:\\111.wav");
s.start();
}
}
class Sound extends Thread{
private String filename;
public Sound(String soundfile){
filename=soundfile;
}
public void run(){
File soundFile=new File(filename);
AudioInputStream audioInputStream=null;
try{
audioInputStream=AudioSystem.getAudioInputStream(soundFile);
}catch(Exception e){
e.printStackTrace();
return;
}
AudioFormat format=audioInputStream.getFormat();
SourceDataLine auline=null;
DataLine.Info info =new DataLine.Info(SourceDataLine.class, format);
try{
auline=(SourceDataLine)AudioSystem.getLine(info);
auline.open(format);
}catch(Exception e){
e.printStackTrace();
return;
}
auline.start();
int nBytesRead=0;
byte[] abData=new byte[1024];
try{
while(nBytesRead!=-1){
nBytesRead=audioInputStream.read(abData, 0, abData.length);
if(nBytesRead>=0){
auline.write(abData, 0, nBytesRead);
}
}
}catch(Exception e){
e.printStackTrace();
return;
}finally{
auline.drain();
auline.close();
}
}
}
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class Test {
public static void main(String[] args) {
Sound s=new Sound("E:\\111.wav");
s.start();
}
}
class Sound extends Thread{
private String filename;
public Sound(String soundfile){
filename=soundfile;
}
public void run(){
File soundFile=new File(filename);
AudioInputStream audioInputStream=null;
try{
audioInputStream=AudioSystem.getAudioInputStream(soundFile);
}catch(Exception e){
e.printStackTrace();
return;
}
AudioFormat format=audioInputStream.getFormat();
SourceDataLine auline=null;
DataLine.Info info =new DataLine.Info(SourceDataLine.class, format);
try{
auline=(SourceDataLine)AudioSystem.getLine(info);
auline.open(format);
}catch(Exception e){
e.printStackTrace();
return;
}
auline.start();
int nBytesRead=0;
byte[] abData=new byte[1024];
try{
while(nBytesRead!=-1){
nBytesRead=audioInputStream.read(abData, 0, abData.length);
if(nBytesRead>=0){
auline.write(abData, 0, nBytesRead);
}
}
}catch(Exception e){
e.printStackTrace();
return;
}finally{
auline.drain();
auline.close();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询