转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-audio-playing-pcm-amplitude-array.html
How to play a array of PCM amplitude values (integer or float array) in Java - Steps
Basic Steps :
//initialize source data line - for playback SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat); line.open(audioFormat); line.start(); //play the byteArray line.write(byteArray, 0, byteArray .length);//(byte[] b, int off, int len) line.drain(); line.close();
Converting integer array to bytearray :
We need to convert our PCM array to byteArray because the line.write requires byte[] b as parameter.
byte b = (byte)(i*127f);
Full code : This example plays the randomly generated array :
public class PlayAnArray { private static int sampleRate = 16000; public static void main(String[] args) { try { final AudioFormat audioFormat = new AudioFormat(sampleRate, 8, 1, true, true); SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat ); line.open(audioFormat ); line.start(); for (int i = 0; i < 5; i++) {//repeat in loop play(line, generateRandomArray()); } line.drain(); line.close(); } catch (Exception e) { e.printStackTrace(); } } private static byte[] generateRandomArray() { int size = 20000; System.out.println(size); byte[] byteArray = new byte[size]; for (int i = 0; i < size; i++) { byteArray[i] = (byte) (Math.random() * 127f); } return byteArray; } private static void play(SourceDataLine line, byte[] array) { int length = sampleRate * array.length / 1000; line.write(array, 0, array.length); } }
You may modify generateRandomArray to play different waveforms like SINE wave, square wave... etc
For playing a wave file in java follow my post on How to play wave file on java
本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。