java 实现循环播放wav文件

来源:互联网 发布:志村团藏 知乎 编辑:程序博客网 时间:2024/05/22 15:54

package com.hf.app.lucky.comm;

import java.io.File;

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 javazoom.jlgui.basicplayer.BasicPlayerEvent;

import com.hf.app.lucky.config.DesignPanelConfigTitle;
import com.hf.app.lucky.design.DesignPanelTitle;

public class PlayerWav {

 // 播放器使用单例模式
 private static PlayerWav instace = null;

 public static PlayerWav getInstance() {
  if (instace == null) {
   instace = new PlayerWav();
  }
  return instace;
 }

 private PlayerWav() {
 }

 // PlayerCTL
 private PlayerCTL playerCTL = null;

 public PlayerCTL getPlayerCTL() {
  if (playerCTL == null) {
   playerCTL = new PlayerCTL();
  }
  return playerCTL;
 }

 // wav文件名
 private String strSongFileName = null;

 public String getSongFileName() {
  return strSongFileName;
 }

 public void setSongFileName(String szSongFileName) {
  if (strSongFileName == null) {
   strSongFileName = new String(szSongFileName);
  } else {
   strSongFileName = szSongFileName;
  }
 }

 public class PlayerCTL {
  File wavFile = null;

  // 打开文件
  public void openSong(String strFileName) {
   try {
    wavFile = new File(getSongFileName());
   } catch (Exception ex) {
    ex.printStackTrace();
   }
  }

  // 播放文件
  public void play() {
   try {
    AudioInputStream ais = AudioSystem.getAudioInputStream(wavFile);
    AudioFormat af = ais.getFormat();
    SourceDataLine sdl = null;
    DataLine.Info dinfo = new DataLine.Info(SourceDataLine.class,
      af);
    sdl = (SourceDataLine) AudioSystem.getLine(dinfo);
    sdl.open(af);
    byte[] lbytes = new byte[sdl.available()];
    int lReadBytes = 0;
    sdl.start();
    while (lReadBytes != -1) {
     lReadBytes = ais.read(lbytes, 0, lbytes.length);
     if (lReadBytes > 0) {
      sdl.write(lbytes, 0, lReadBytes);
     }
    }
    
    // 是否持续播放
    // 循环播放,只有在设置为循环播放时才使用循环播放功能
    // 单次播放和不播放情况下均不进行循环动作
    DesignPanelConfigTitle designPanelConfigTitle = DesignPanelTitle
    .getInstance().getConfig();
    int nPlayType = designPanelConfigTitle.getBakSndDisType();
    switch (nPlayType) {
    case LuckyChooserConst.SND_DIS_TYPE_DISVISIBLE:
     break;
    case LuckyChooserConst.SND_DIS_TYPE_SINGLE:
     break;
    case LuckyChooserConst.SND_DIS_TYPE_LOOP:
     getPlayerCTL().openSong(getSongFileName());
     getPlayerCTL().play();
     break;
    default:
    }
   } catch (Exception ex) {
    ex.printStackTrace();
   }
  }
 }

 public void playSong(String strFilePath) {
  setSongFileName(strFilePath);
  getPlayerCTL().openSong(getSongFileName());
  getPlayerCTL().play();
 }
}

原创粉丝点击