Java Sound : audio inputstream from pcm amplitude array
2024-08-26 14:04:35
转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-sound-making-audio-input-stream.html
In this post, i am going to show the code for creating the AudioInputStream from an PCM - amplitude array.
It basically converts the int [] array to byte array according to AudioFormat.
The code for the reverse operation (extract amplitude array from recorded wave file or AudioStream )is in my
earlier post : http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-extract-amplitude-array-from.html
The code for converting PCM amplitude array to AudioStream is follows :
public static AudioInputStream getAudioStreamFromPCMArray(int[] audioDataIntArr, AudioFormat format) {
byte[] data = null;
int nlengthInSamples = audioDataIntArr.length * 2;
if (format.getSampleSizeInBits() == 16) {
// FIXME: debug at full length, signed/unsigned problem
data = new byte[nlengthInSamples];
if (format.isBigEndian()) {
for (int i = 0; i < audioDataIntArr.length; i++) {
int temp = Math.abs((short) (audioDataIntArr[i] * 255));
data[2 * i + 1] = (byte) temp;
data[2 * i + 0] = (byte) (temp >> 8);
}
} else {
for (int i = 0; i < audioDataIntArr.length; i++) {
int temp = Math.abs((short) (audioDataIntArr[i] * 255));
data[2 * i + 0] = (byte) temp;
data[2 * i + 1] = (byte) (temp >> 8);
}
}
} else if (format.getSampleSizeInBits() == 8) {
nlengthInSamples = audioDataIntArr.length;
data = new byte[nlengthInSamples];
if (format.getEncoding().toString().startsWith("PCM_SIGN")) {
// PCM_SIGNED
for (int i = 0; i < nlengthInSamples; i++) {
data[i] = (byte) audioDataIntArr[i];
}
} else {
// PCM_UNSIGNED
for (int i = 0; i < nlengthInSamples; i++) {
data[i] = (byte) (audioDataIntArr[i] + 128);
}
}
}// end of if..else
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, format, audioDataIntArr.length);
return ais;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//## Required Testing -- Comments are much welcomed ...... Thanks
最新文章
- MathType应用:批量改变公式格式
- Objective-C文章中的生词
- python(28)获得网卡的IP地址
- CSS核心的几个概念
- scala - Map基础
- Springmvc整合tiles框架简单入门示例(maven)
- web.xml配置bug之提示The content of element type ";web-app"; must match ";(icon?,display- name?,description?,distributable?,
- hdoj 5389 Zero Escape
- openstack nova数据库计算结点IP地址
- Sequence
- Java的Date类与Calendar类
- PHP的抽象类、接口类的区别和选择【转载】
- 只为粗暴看一下ES6的字符串模板的性能
- 谈谈CommonsChunkPlugin抽取公共模块
- Java爬虫----有道翻译初步
- oracle有三种类型的异常错误: 预定义 ( Predefined )错误里面的常见错误
- Java+Selenium向文本框输入内容以后模仿键盘的";ENTRY";
- 洛谷P1012 拼数 string
- AT91RM9200---电源管理控制器(PMC)介绍
- spring boot 2.0(二)动态banner的支持