【Java】实现wav格式音乐的 播放、停止、循环播放、音量调节

前言

最近一段时间,学校请了达内的老师给我们上Java初级实训课。实训上完后,分组选题,做小游戏。我们小组选了 泡泡堂,小组将近5天的协作编码,终于差不多做完了。之后我也会把一些收获的东西抽离出来,总结到博客上去。

期间我有负责游戏音效、BGM的工作,经上网查询资料,自己写了一个简单的音乐播放类,来满足我们的游戏的需求。该工具类,没有调用其他第三方jar包,用的是JDK底层API。只支持wav格式的音乐文件。

代码

MusicPlayer.java

package com.tedu.manager;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Control;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * 根据jdk底层API实现的音乐播放器
 * 
 * @功能
 * 1、只支持wav,且只能播放一首
 * 2、可循环播放,随时停止(并非暂停)
 * 3、支持一定范围内的音量调节
 * 
 * 参考博客:
 * https://blog.csdn.net/qq_21907023/article/details/96174077
 * https://blog.csdn.net/fuckcdn/article/details/83725725
 * 
 * @author passerbyYSQ
 * @create 2020年7月20日 下午4:05:50
 */
public class MusicPlayer {
//	private AudioInputStream audioIn;
//	private SourceDataLine sourceDataLine;
	// wav文件的路径
	private File file;
	// 是否循环播放
	private volatile boolean isLoop = false;
	// 是否正在播放
	private volatile boolean isPlaying;
	// FloatControl.Type.MASTER_GAIN的值(可用于调节音量)
	private float newVolumn = 7;
	
	private PlayThread playThread;
	
//	public static void main(String[] args) {
//		try {
			MusicPlayer player = new MusicPlayer("F:\\初级软件实训\\音效\\爆炸.wav");
			MusicPlayer player = new MusicPlayer("F:\\初级软件实训\\音效\\放泡泡.mp3");
//			MusicPlayer player = new MusicPlayer("F:\\初级软件实训\\CrazyArcade-master\\music\\bgm0.wav");
//			player.setVolumn(6f).play();
//			System.out.println("开始播放");
//			
//			System.out.println("是否暂停?");
//			Scanner sc = new Scanner(System.in);
//			int isOver = sc.nextInt();
//			if (isOver == 1) {
//				player.over();
//			}
//			
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	
	public MusicPlayer(String srcPath) {
		file = new File(srcPath);
	}
	
	/**
	 * 播放音乐
	 */
	public void play() {
        if (playThread == null) {
            playThread = new PlayThread();
		    playThread.start();
        }
	}
	
	/**
	 * 结束音乐(并非暂停)
	 */
	public void over() {
		isPlaying = false;
		if (playThread != null) {
			playThread = null;
		}
	}
	
	/**
	 * 设置循环播放
	 * @param isLoop
	 * @return	返回当前对象
	 */
	public MusicPlayer setLoop(boolean isLoop) {
		this.isLoop = isLoop;
		return this;
	}
	
	/**
	 * -80.0~6.0206测试,越小音量越小
	 * @param newVolumn
	 * @return	返回当前对象
	 */
	public MusicPlayer setVolumn(float newVolumn) {
		this.newVolumn = newVolumn;
		return this;
	}
	
	/**
	 * 异步播放线程
	 */
	private class PlayThread extends Thread {
	
		@Override
		public void run() {
			isPlaying = true;
			do {
//				isPlaying = true;
				
				SourceDataLine sourceDataLine = null;
				BufferedInputStream bufIn = null;
				AudioInputStream audioIn = null;
				try {
					bufIn = new BufferedInputStream(new FileInputStream(file));
					audioIn = AudioSystem.getAudioInputStream(bufIn); // 可直接传入file
					
					AudioFormat format = audioIn.getFormat();
					sourceDataLine = AudioSystem.getSourceDataLine(format);
					sourceDataLine.open();
					// 必须open之后
					if (newVolumn != 7) {
						FloatControl control = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);
//						System.out.println(control.getMaximum());
//						System.out.println(control.getMinimum());
						control.setValue(newVolumn);
					}
					
					sourceDataLine.start();
					byte[] buf = new byte[512];
//					System.out.println(audioIn.available());
					int len = -1;
					while (isPlaying && (len = audioIn.read(buf)) != -1) {
						sourceDataLine.write(buf, 0, len);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					
					if (sourceDataLine != null) {
						sourceDataLine.drain(); 
						sourceDataLine.close();
					}
					try {
						if (bufIn != null) {
							bufIn.close();
						}
						if (audioIn != null) {
							audioIn.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} while (isPlaying && isLoop);
		}
	}
	
	
}

  • 5
    点赞
  • 61
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
Java播放wav音频功能的实现代码,播放wav音频,压缩包中带有测试音频,是否能播放 MP3,未知。   boolean looping = false; //是否循环播放   String[] choics = { "chimes.wav", "start.wav" }; //声音文件名数组   URL file1 = getClass().getResource(choics[0]); //声音文件1   URL file2 = getClass().getResource(choics[1]); //声音文件2   AudioClip sound1 = java.applet.Applet.newAudioClip(file1); //声音剪辑对象1   AudioClip sound2 = java.applet.Applet.newAudioClip(file2); //声音剪辑对象2   AudioClip chosenClip = sound1; //选择的声音剪辑对象   JComboBox jcbFiles = new JComboBox(choics); //文件选择组合框   JButton playButton = new JButton("播放"); //播放按钮   JButton loopButton = new JButton("循环播放"); //循环播放按钮   JButton stopButton = new JButton("停止"); //停止播放按钮   JLabel status = new JLabel("选择播放文件"); //状态栏标签   JPanel controlPanel = new JPanel(); //控制面板用于包容按钮   Container container = getContentPane(); //获得窗口内容窗格   public AudioPlayDemo() { //构造器    super("声音播放程序"); //调用父类构造器设置窗口标题栏    jcbFiles.setSelectedIndex(0); //设置组合框选择项    jcbFiles.addItemListener(this); //为播放按钮添加项目监听器    //为播放按钮、循环播放按钮、停止播放按钮添加动作监听器    playButton.addActionListener(this);    loopButton.addActionListener(this);    stopButton.addActionListener(this);    stopButton.setEnabled(false); //设置停止播放按钮不可用    //把播放按钮、循环播放按钮、停止播放按钮加入控制面板    controlPanel.add(playButton);    controlPanel.add(loopButton);    controlPanel.add(stopButton);    //把文件选择组合框、控制面板、状态栏标签加入到窗口内容窗格    container.add(jcbFiles, BorderLayout.NORTH);    container.add(controlPanel, BorderLayout.CENTER);    container.add(status, BorderLayout.SOUTH);    setSize(300, 130); //设置窗口大小    setVisible(true); //设置窗口可视    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序   }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值