Java中音频的加载(AudioSystem)

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:02   1353   0

通过类加载器,将音频播放。

package com.ctgu;
import java.io.File;
import java.io.IOException;

import javax.sound.sampled.*;


public class Sound {

 byte[] data;
 AudioFormat format;
 int length;
 
 public Sound(String name) throws Exception{
  AudioInputStream in = AudioSystem.getAudioInputStream(getClass().getResource(name));
  format = in.getFormat();
  length = (int)in.getFrameLength();
  data = new byte[length];
  in.read(data);
  in.close();
 }
 
 public void play(){
  Runnable runnable = new Runnable() {
   
   @Override
   public void run() {
    try {
     Clip clip = AudioSystem.getClip();
     clip.open(format, data, 0, length);
     clip.start();
    // System.out.println(new String(data,0,length));
//     clip.drain();
//     clip.stop();
//     clip.close();
    } catch (LineUnavailableException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  };
  new Thread(runnable).start();
  
 }
}

ps:文件一定要放在Java包下面

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP