- 介绍
用Java该怎么实现录音以及播放声音的效果呢?
- 录音
[codesyntax lang="java"]
/** * Copyright By suren. * You can get more information from my website: * http://surenpi.com */ package org.suren.talk.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.SocketException; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine; /** * 声音录制的工具类 * @author suren * @date 2015年8月23日 上午8:58:34 */ public class RecordUtil { private boolean done = false; private ByteArrayOutputStream bufStream = new ByteArrayOutputStream(); private TargetDataLine dataLine; public void start() { System.out.println("start record"); try { init(); int len = 1024; byte[] buf = new byte[len]; while(!done && (len = dataLine.read(buf, 0, 1024)) != -1) { bufStream.write(buf, 0, len); } } catch (LineUnavailableException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } } /** * @throws LineUnavailableException * @throws SocketException * */ public void init() throws LineUnavailableException, SocketException { if(dataLine == null) { dataLine = AudioSystem.getTargetDataLine(null); dataLine.open(); dataLine.start(); } done = false; } public byte[] getData() { byte[] data = bufStream.toByteArray(); bufStream.reset(); return data; } public void finish() throws IOException { done = true; if(getData() == null) { return; } } public void close() { if(dataLine != null && dataLine.isOpen()) { dataLine.close(); } } }
[/codesyntax]
上面的代码是一个录音的工具类。
- 播放
[codesyntax lang="java"]
/** * Copyright By suren. * You can get more information from my website: * http://surenpi.com */ package org.suren.talk.util; import java.io.ByteArrayOutputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; /** * 用于播放声音的工具类 * @author suren * @date 2015年8月23日 下午7:04:22 */ public class PlayerUtil { private SourceDataLine dataLine; public void init() throws LineUnavailableException { dataLine = AudioSystem.getSourceDataLine(null); dataLine.open(); dataLine.start(); } public void play(ByteArrayOutputStream byteStream) { if(byteStream == null) { System.err.println("byteStream is null"); return; } byte[] data = byteStream.toByteArray(); byteStream.reset(); play(data); } public void play(byte[] data) { if(data == null) { return; } play(data, 0, data.length); } public void play(byte[] data, int off, int length) { if(dataLine.isOpen()) { dataLine.write(data, off, length); } } public void stop() { dataLine.close(); } }
[/codesyntax]