本文实例为大家分享了java实现播放背景音乐的具体代码,供大家参考,具体内容如下
测试源码
播放背景音乐类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package forGame;
import javax.sound.sampled.*;
import java.io.File;
//测试背景音乐播放(只能播放.wav文件)
public class Demo_2 {
//需要传入要播放的文件
void playMusic(File file)
{
try
{
//创建相当于音乐播放器的对象
Clip clip = AudioSystem.getClip();
//将传入的文件转成可播放的文件
AudioInputStream audioInput = AudioSystem.getAudioInputStream(file);
//播放器打开这个文件
clip.open(audioInput);
//clip.start();//只播放一次
//循环播放
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (Exception ex){
ex.printStackTrace();
}
//死循环不让主程序结束(swing可不用)
/*
while(true){
}
*/
}
}
|
窗口类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
package forGame;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
//动态效果
public class Demo_1 extends JFrame{
//背景
private BufferedImage bufferedImage;
//窗体大小
private int width;
private int height;
//照片数组
private BufferedImage[] images = new BufferedImage[ 4 ];
//要绘制动态图片中的那张
private BufferedImage image;
//背景音乐
private File bgm;
//播放音乐类对象
private Demo_2 demo_2 = new Demo_2();
//初始化
{
if (bufferedImage == null ){
try {
bufferedImage = ImageIO.read( new File( "src\\image\\背景.png" ));
for ( int i = 1 ;i < images.length + 1 ;i ++)
images[i - 1 ] = ImageIO.read( new File( "src\\image\\大飞机爆炸" + i + ".png" ));
} catch (IOException e) {
e.printStackTrace();
}
}
width = bufferedImage.getWidth();
height = bufferedImage.getHeight();
image = images[ 0 ];
bgm = new File( "src\\music\\bgm.wav" );
}
public Demo_1(){
super ( "动态测试" );
//设置窗口
setSize(width,height);
setLocationRelativeTo( null );
setResizable( false );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible( true );
//启动线程
MyThread myThread = new MyThread();
myThread.start();
//播放背景音乐
demo_2.playMusic(bgm);
}
//双缓冲绘制解决图片闪烁问题
@Override
public void paint(Graphics g) {
Image image = this .createImage(width,height);
Graphics gImage = image.getGraphics();
gImage.setColor(gImage.getColor());
gImage.fillRect( 0 , 0 ,width,height);
super .paint(gImage);
//绘制背景
gImage.drawImage(bufferedImage, 0 , 0 , null );
//绘制动态图片
gImage.drawImage( this .image, 0 , 100 , null );
//最后绘制缓冲后的图片
g.drawImage(image, 0 , 0 , null );
}
private int num = 0 ; //images数组内图片索引
//线程内部类
private class MyThread extends Thread{
@Override
public void run() {
while ( true ) {
if (num <= 3 ) {
image = images[num ++];
}
else
num = 0 ;
repaint();
try {
sleep( 100 ); //每隔100毫秒重绘一次
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Demo_1();
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_46085748/article/details/113413948