diff --git a/src/com/sheep/music/BackgroundMusic.java b/src/com/sheep/music/BackgroundMusic.java new file mode 100644 index 0000000..8f15b06 --- /dev/null +++ b/src/com/sheep/music/BackgroundMusic.java @@ -0,0 +1,45 @@ +package com.sheep.music; + +import javax.sound.sampled.*; +import java.io.File; +import java.io.IOException; + +public class BackgroundMusic { + private Clip clip; + private String name1 = "wavs\\告白气球.wav"; + + public void play(String musicFilePath){ + try { + File musicFile = new File(musicFilePath); + AudioInputStream audioIn = AudioSystem.getAudioInputStream(musicFile); + clip = AudioSystem.getClip(); + clip.open(audioIn); + clip.loop(Clip.LOOP_CONTINUOUSLY); + } catch (UnsupportedAudioFileException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } catch (LineUnavailableException e) { + throw new RuntimeException(e); + } + } + + public void stop(){ + clip.stop(); + } + + public void switchMusic(Integer gameMode){ + stop(); + switch (gameMode){ + case 1: + play(name1); + break; + case 2: + play(name1); + break; + case 3: + play(name1); + break; + } + } +} diff --git a/src/com/sheep/view/Start.java b/src/com/sheep/view/Start.java index d46d443..cb9a164 100644 --- a/src/com/sheep/view/Start.java +++ b/src/com/sheep/view/Start.java @@ -1,6 +1,7 @@ package com.sheep.view; import com.sheep.model.Brand; +import com.sheep.music.BackgroundMusic; import com.sheep.util.MapUtil; import javax.swing.*; @@ -16,6 +17,7 @@ import java.awt.event.MouseEvent; public class Start extends JFrame { Integer gameMode; JLabel backgroundLabel = new JLabel(new ImageIcon("imgs/背景1.png")); + BackgroundMusic music = new BackgroundMusic(); public Start() { gameMode = 1; @@ -26,6 +28,8 @@ public class Start extends JFrame { //重复刷新 aotoRefresh(); + + music.play("wavs\\告白气球.wav"); } private void init(){ @@ -67,6 +71,7 @@ public class Start extends JFrame { @Override public void mouseClicked(MouseEvent e) { gameMode = 1; + music.switchMusic(1); backgroundLabel.setIcon(new ImageIcon("imgs/背景1.png")); backgroundLabel.repaint(); @@ -78,6 +83,7 @@ public class Start extends JFrame { @Override public void mouseClicked(MouseEvent e) { gameMode = 2; + music.switchMusic(2); backgroundLabel.setIcon(new ImageIcon("imgs/背景2.png")); backgroundLabel.repaint(); @@ -89,6 +95,7 @@ public class Start extends JFrame { @Override public void mouseClicked(MouseEvent e) { gameMode = 3; + music.switchMusic(3); backgroundLabel.setIcon(new ImageIcon("imgs/背景3.png")); backgroundLabel.repaint();