关闭

java 实现循环播放wav文件

1121人阅读 评论(0) 收藏 举报

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();
 }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:191305次
    • 积分:2889
    • 等级:
    • 排名:第13107名
    • 原创:92篇
    • 转载:39篇
    • 译文:0篇
    • 评论:30条
    最新评论