[Java] 播放音频 →→→→→进入此内容的聊天室

来自 , 2020-08-30, 写在 Java, 查看 110 次.
URL http://www.code666.cn/view/1fc21400
  1. //播放声音的类
  2. public class PlaySounds extends Thread {
  3.  
  4.     private String filename;
  5.     public PlaySounds(String wavfile) {
  6.      
  7.         filename = System.getProperty("user.dir")+wavfile;
  8.     }
  9.     public void run() {
  10.  
  11.         File soundFile = new File(filename);
  12.  
  13.         AudioInputStream audioInputStream = null;
  14.         try {
  15.             audioInputStream = AudioSystem.getAudioInputStream(soundFile);
  16.         } catch (Exception e1) {
  17.             e1.printStackTrace();
  18.             return;
  19.         }
  20.  
  21.         AudioFormat format = audioInputStream.getFormat();
  22.         SourceDataLine auline = null;
  23.         DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
  24.  
  25.         try {
  26.             auline = (SourceDataLine) AudioSystem.getLine(info);
  27.             auline.open(format);
  28.         } catch (Exception e) {
  29.             e.printStackTrace();
  30.             return;
  31.         }
  32.  
  33.         auline.start();
  34.         int nBytesRead = 0;
  35.         //这是缓冲
  36.         byte[] abData = new byte[512];
  37.  
  38.         try {
  39.             while (nBytesRead != -1) {
  40.                 nBytesRead = audioInputStream.read(abData, 0, abData.length);
  41.                 if (nBytesRead >= 0)
  42.                     auline.write(abData, 0, nBytesRead);
  43.             }
  44.         } catch (IOException e) {
  45.             e.printStackTrace();
  46.             return;
  47.         } finally {
  48.             auline.drain();
  49.             auline.close();
  50.         }
  51.  
  52.     }  
  53. }
  54.  

回复 "播放音频"

这儿你可以回复上面这条便签

captcha