您的位置:首页 > 运维架构

J2se中的声音---AudioPlayer

2016-07-07 15:05 323 查看
1 package cn.gp.tools;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

/**
* 背景音效工具类
* @author 小风微灵
*
*/
public class MusicUtil {

/**
* 播放触发音效
* @param isPlay    是否播放
* @param pathIndex    播放序列
*/
public static void playMusic(boolean isPlay,int pathIndex) {
// 打 开 一 个 声 音 文 件 流 作 为 输 入
InputStream in;
try {
String musicPath=ImageUtil.getProgramRootPath()+"music/btn_music_"+pathIndex+".wav";
in = new FileInputStream (musicPath);
//System.out.println("音乐路径:"+musicPath);
AudioStream as = new AudioStream (in); // 用 输 入 流 创 建 一 个AudioStream 对 象
//System.out.println("成功转换成音乐流:");
if(isPlay){//【改为:isPlay后音效恢复】
AudioPlayer.player.start (as); //“player” 是AudioPlayer 中 一 静 态 成 员 用 于 控 制 播 放
//System.err.println("音乐播放中....");
}else{
AudioPlayer.player.stop (as);
//System.err.println("音乐停止....");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 播放指定音乐
* @param isPlay        是否播放
* @param musicName        音乐名称
*/
public static void playMusic(boolean isPlay,String musicName) {
// 打 开 一 个 声 音 文 件 流 作 为 输 入
InputStream in = null;
AudioStream as = null;
try {
String musicPath=ImageUtil.getProgramRootPath()+"music/"+musicName;
in = new FileInputStream (musicPath);
//System.out.println("音乐路径:"+musicPath);
as = new AudioStream (in); // 用 输 入 流 创 建 一 个AudioStream 对 象
//System.out.println("成功转换成音乐流:");
if(isPlay){
AudioPlayer.player.start (as); //“player” 是AudioPlayer 中 一 静 态 成 员 用 于 控 制 播 放
//System.err.println("音乐播放中....");
}else{
AudioPlayer.player.stop (as);
//System.err.println("音乐停止....");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
as.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
/**
* 默认播放的音效
* @param isPlay    是否播放
*/
public static void playMusic(boolean isPlay) {
// 打 开 一 个 声 音 文 件 流 作 为 输 入
InputStream in;
try {
String musicPath=ImageUtil.getProgramRootPath()+"music/btn_music_5.wav";
in = new FileInputStream (musicPath);
//System.out.println("音乐路径:"+musicPath);
AudioStream as = new AudioStream (in); // 用 输 入 流 创 建 一 个AudioStream 对 象
//System.out.println("成功转换成音乐流:");
if(isPlay){
AudioPlayer.player.start (as); //“player” 是AudioPlayer 中 一 静 态 成 员 用 于 控 制 播 放
//System.err.println("音乐播放中....");
}else{
AudioPlayer.player.stop (as);
//System.err.println("音乐停止....");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: