⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sound.java

📁 wiziqi
💻 JAVA
字号:
package vo.sounds;

import java.io.File;
import java.io.IOException;

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;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {
  String[] sounds = { "mis/PUTCHESS.WAV", "mis/WIN.WAV", "mis/LOSS.WAV" };

  private AudioInputStream ais;

  private SourceDataLine line;

  private AudioFormat baseFormat;

  private static final int BUFFER_SIZE = 4000 * 4;
  
  /** 用于实现单子模式 */
  private static Sound soundTem = null;

  /**
   * 落子的声音
   */
  public static int PUTCHESS = 0;

  /**
   * 表示赢
   */
  public static int WIN = 1;

  /**
   * 输掉游戏的声音
   */
  public static int LOSS = 2;

  private Sound() {
    super();
  }
  
  public static Sound getSound() {
    if(soundTem == null) {
      soundTem = new Sound();
      return soundTem;
    } else {
      return soundTem;
    }
  }

  private SourceDataLine getLine(AudioFormat audioFormat) {
    SourceDataLine res = null;
    DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
    try {
      res = (SourceDataLine) AudioSystem.getLine(info);
      res.open(audioFormat);
    } catch (Exception e) {
    }
    return res;
  }

  public void play(int sound) {
    try {
      ais = AudioSystem.getAudioInputStream(new File(sounds[sound]));
      baseFormat = ais.getFormat();

      line = getLine(baseFormat);
      line.start();
      int inBytes = 0;
      byte[] audioData = new byte[BUFFER_SIZE];
      while (inBytes != -1) {
        inBytes = ais.read(audioData, 0, BUFFER_SIZE);
        if (inBytes >= 0) {
          line.write(audioData, 0, inBytes);
        }
      }
    } catch (IOException ex) {
      System.out.println(ex.getMessage());
    } catch (UnsupportedAudioFileException ex) {
      System.out.println(ex.getMessage());
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -