Sound.java
Upload User: shjixinjx
Upload Date: 2020-12-29
Package Size: 985k
Code Size: 2k
Category:

Games

Development Platform:

Java

  1. package kyodai;
  2. import java.io.*;
  3. import javax.sound.sampled.*;
  4. import java.net.*;
  5. /**
  6.  * 控制音乐特效
  7.  */
  8. public class Sound implements Runnable {
  9. String currentName;
  10. Object currentSound;
  11. Thread thread;
  12. String[] filename = {
  13. "sound/select.wav", "sound/earse.wav", "sound/bomb.wav",
  14. "sound/refresh.wav", "sound/hint.wav"};
  15. public static int SELECT = 0;
  16. public static int EARSE = 1;
  17. public static int BOMB = 2;
  18. public static int REFRESH = 3;
  19. public static int HINT = 4;
  20. public Sound(int sound) {
  21. if (sound < 0 || sound > 4) {
  22. return;
  23. }
  24. URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader();
  25. URL url = urlLoader.findResource(filename[sound]);
  26. try {
  27. currentSound = AudioSystem.getAudioInputStream(url);
  28. }
  29. catch (Exception ex1) {
  30. currentSound = null;
  31. return;
  32. }
  33. if (currentSound instanceof AudioInputStream) {
  34. try {
  35. AudioInputStream stream = (AudioInputStream) currentSound;
  36. AudioFormat format = stream.getFormat();
  37. DataLine.Info info = new DataLine.Info(
  38. Clip.class,stream.getFormat(),
  39. ( (int) stream.getFrameLength() *
  40.  format.getFrameSize()));
  41. Clip clip = (Clip) AudioSystem.getLine(info);
  42. clip.open(stream);
  43. currentSound = clip;
  44. }
  45. catch (Exception ex) {
  46. currentSound = null;
  47. return;
  48. }
  49. }
  50. if (currentSound != null) {
  51. start();
  52. }
  53. }
  54. public void playSound() {
  55. if (currentSound instanceof Clip) {
  56. Clip clip = (Clip) currentSound;
  57. clip.start();
  58. try {
  59. thread.sleep(999);
  60. }
  61. catch (Exception e) {
  62. }
  63. while (clip.isActive() && thread != null) {
  64. try {
  65. thread.sleep(99);
  66. }
  67. catch (Exception e) {
  68. break;
  69. }
  70. }
  71. clip.stop();
  72. clip.close();
  73. }
  74. currentSound = null;
  75. }
  76. public void start() {
  77. thread = new Thread(this);
  78. thread.start();
  79. }
  80. public void run() {
  81. playSound();
  82. stop();
  83. }
  84. public void stop() {
  85. if (thread != null) {
  86. thread.interrupt();
  87. }
  88. thread = null;
  89. }
  90. }