转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-extract-amplitude-array-from.html

Extract amplitude array from recorded/saved wav : From File , AudioInputStream , ByteArray of File or ByteArrayInputStream - working java source code example

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* saving and extracting amplitude data from wavefile byteArray
*
* @author Ganesh Tiwari
*/
public class WaveData {
private byte[] arrFile;
private byte[] audioBytes;
private int[] audioData;
private ByteArrayInputStream bis;
private AudioInputStream audioInputStream;
private AudioFormat format;
private double durationSec;
private double durationMSec;
public WaveData() {
}
public int[] extractAmplitudeFromFile(File wavFile) {
try {
// create file input stream
FileInputStream fis = new FileInputStream(wavFile);
// create bytearray from file
arrFile = new byte[(int) wavFile.length()];
fis.read(arrFile);
} catch (Exception e) {
System.out.println("SomeException : " + e.toString());
}
return extractAmplitudeFromFileByteArray(arrFile);
}
public int[] extractAmplitudeFromFileByteArray(byte[] arrFile) {
// System.out.println("File : "+wavFile+""+arrFile.length);
bis = new ByteArrayInputStream(arrFile);
return extractAmplitudeFromFileByteArrayInputStream(bis);
}
/**
* for extracting amplitude array the format we are using :16bit, 22khz, 1
* channel, littleEndian,
*
* @return PCM audioData
* @throws Exception
*/
public int[] extractAmplitudeFromFileByteArrayInputStream(ByteArrayInputStream bis) {
try {
audioInputStream = AudioSystem.getAudioInputStream(bis);
} catch (UnsupportedAudioFileException e) {
System.out.println("unsupported file type, during extract amplitude");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException during extracting amplitude");
e.printStackTrace();
}
// float milliseconds = (long) ((audioInputStream.getFrameLength() *
// 1000) / audioInputStream.getFormat().getFrameRate());
// durationSec = milliseconds / 1000.0;
return extractAmplitudeDataFromAudioInputStream(audioInputStream);
}
public int[] extractAmplitudeDataFromAudioInputStream(AudioInputStream audioInputStream) {
format = audioInputStream.getFormat();
audioBytes = new byte[(int) (audioInputStream.getFrameLength() * format.getFrameSize())];
// calculate durations
durationMSec = (long) ((audioInputStream.getFrameLength() * 1000) / audioInputStream.getFormat().getFrameRate());
durationSec = durationMSec / 1000.0;
// System.out.println("The current signal has duration "+durationSec+" Sec");
try {
audioInputStream.read(audioBytes);
} catch (IOException e) {
System.out.println("IOException during reading audioBytes");
e.printStackTrace();
}
return extractAmplitudeDataFromAmplitudeByteArray(format, audioBytes);
}
public int[] extractAmplitudeDataFromAmplitudeByteArray(AudioFormat format, byte[] audioBytes) {
// convert
// TODO: calculate duration here
audioData = null;
if (format.getSampleSizeInBits() == 16) {
int nlengthInSamples = audioBytes.length / 2;
audioData = new int[nlengthInSamples];
if (format.isBigEndian()) {
for (int i = 0; i < nlengthInSamples; i++) {
/* First byte is MSB (high order) */
int MSB = audioBytes[2 * i];
/* Second byte is LSB (low order) */
int LSB = audioBytes[2 * i + 1];
audioData[i] = MSB << 8 | (255 & LSB);
}
} else {
for (int i = 0; i < nlengthInSamples; i++) {
/* First byte is LSB (low order) */
int LSB = audioBytes[2 * i];
/* Second byte is MSB (high order) */
int MSB = audioBytes[2 * i + 1];
audioData[i] = MSB << 8 | (255 & LSB);
}
}
} else if (format.getSampleSizeInBits() == 8) {
int nlengthInSamples = audioBytes.length;
audioData = new int[nlengthInSamples];
if (format.getEncoding().toString().startsWith("PCM_SIGN")) {
// PCM_SIGNED
for (int i = 0; i < audioBytes.length; i++) {
audioData[i] = audioBytes[i];
}
} else {
// PCM_UNSIGNED
for (int i = 0; i < audioBytes.length; i++) {
audioData[i] = audioBytes[i] - 128;
}
}
}// end of if..else
// System.out.println("PCM Returned===============" +
// audioData.length);
return audioData;
}
public byte[] getAudioBytes() {
return audioBytes;
}
public double getDurationSec() {
return durationSec;
}
public double getDurationMiliSec() {
return durationMSec;
}
public int[] getAudioData() {
return audioData;
}
public AudioFormat getFormat() {
return format;
}
}

留言:

Think I found a bug for 8 bit unsigned samples in the code above.

Java regards a byte-variable as a signed variable, so we can't just subtract 128 for all sample-values. For "negative" values we must instead add 128, I think.

E.g. the sampled unsigned value 10000000 (128 unsigned) should mean that we are in the middle of the value-range. It should actually mean 0, but java sees it as -128, and if we subtract 128 we'll get -256, which isn't what we want at all.

And the "highest" sample-value possible with 8 bits, 11111111, means -1 to java if it's in a byte-variable. We'd get the value -129 here with the old method, but we would expect 127.

For all "positive" values 00000000 - 01111111 it works fine to subtract 128 as before, so something like this would work better:

// PCM_UNSIGNED
for (int i = 0; i < audioBytes.length; i++)
{
if (audioBytes[i] >= 0)
_audioData[i] = audioBytes[i] - 128;
else
_audioData[i] = audioBytes[i] + 128;
}

(Or e.g. you could "shift" the byte-value into an int-variable before subtracting 128.)

Java extract amplitude array from recorded wave的更多相关文章

  1. Java Sound : audio inputstream from pcm amplitude array

    转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-sound-making-audio-input-stream.html In ...

  2. Java之数组array和集合list、set、map

    之前一直分不清楚java中的array,list.同时对set,map,list的用法彻底迷糊,直到看到了这篇文章,讲解的很清楚. 世间上本来没有集合,(只有数组参考C语言)但有人想要,所以有了集合 ...

  3. Java – Check if Array contains a certain value?

    Java – Check if Array contains a certain value?1. String Arrays1.1 Check if a String Array contains ...

  4. java 编程基础 Class对象 反射 :数组操作java.lang.reflect.Array类

    java.lang.reflect包下还提供了Array类 java.lang.reflect包下还提供了Array类,Array对象可以代表所有的数组.程序可以通过使 Array 来动态地创建数组, ...

  5. Java Audio : Playing PCM amplitude Array

    转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-audio-playing-pcm-amplitude-array.html ...

  6. java中List Array相互转换

    List to Array List 提供了toArray的接口,所以可以直接调用,转为object型数组 List<String> list = new ArrayList<Str ...

  7. Java中对Array数组的常用操作

    目录: 声明数组: 初始化数组: 查看数组长度: 遍历数组: int数组转成string数组: 从array中创建arraylist: 数组中是否包含某一个值: 将数组转成set集合: 将数组转成li ...

  8. JAVA中数组Array与List互转

    List<String> list = new ArrayList<String>();String[] array = new String[10]; 1.数组转成Listl ...

  9. Java List 和 Array 转化

    List to Array List 提供了toArray的接口,所以可以直接调用转为object型数组 List<String> list = new ArrayList<Stri ...

随机推荐

  1. 华硕ASUS U5800GE驱动

    重要的触摸板 微软商店 ASUS Keyboard Hotkeys 设备管理器 人体学输入设备 ASUS Precision Touchpad (ScreenPad) Asus ScreenPad D ...

  2. linux学习6 Linux系统组成及初始

    一.linux发行版回顾 1.版本回顾 2.Linux基础 a.CPU架构 32位CPU: X86 64位CPU:X64因为最早的X64位CPU是amd公司生产的所以也叫 amd64(可以兼容X86) ...

  3. YAML_13 嵌套循环,循环添加多用户

    with_nested ansible]# vim add1.yml --- - hosts: web2   remote_user: root   vars:     un: [a, b, c]   ...

  4. 2017.10.3 国庆清北 D3T2 公交车

    题目描述 LYK在玩一个游戏. 有k群小怪兽想乘坐公交车.第i群小怪兽想从xi出发乘坐公交车到yi.但公交车的容量只有M,而且这辆公交车只会从1号点行驶到n号点. LYK想让小怪兽们尽可能的到达自己想 ...

  5. TFRecord 使用

    tfrecord生成 import os import xmltodict import tensorflow as tf import numpy as np dir_path = 'F:\数据存储 ...

  6. golang-笔记1

    指针: 指针就是地址. 指针变量就是存储地址的变量. *p : 解引用.间接引用. 栈帧: 用来给函数运行提供内存空间. 取内存于 stack 上. 当函数调用时,产生栈帧.函数调用结束,释放栈帧. ...

  7. 数据结构Java版之邻接矩阵实现图(十一)

    邻接矩阵实现图,是用一个矩阵,把矩阵下标作为一个顶点,如果顶点与顶点之间有边.那么在矩阵对应的点上把值设为 1 .(默认是0) package mygraph; import java.util.Li ...

  8. BurpSuite intuder里保存所有网页的特定内容:以bugku的cookies欺骗为例题

    这题里想读取index.php只能一行一行的读,通过控制line参数的值.如下: 正常的writeup都是写个爬虫,但我觉得burp肯定有自带这种功能,不用重造轮子.经过学习后发现以下步骤可以实现. ...

  9. Oracle表空间 与 分页

    目录 Oracle表空间 表空间的构建以及数据文件的挂接 创建一个用户,并指定专有的永久表空间和临时表空间 伪列 分页 Oracle表空间 一个表空间可以包含1至n个数据文件 一个数据文件必然属于某个 ...

  10. PHP 浮点型运算相关问题

    php 浮点数计算比较及取整不准确.举例: $a = 0.2+0.7; $b = 0.9; var_dump($a == $b); //输出的结果为bool(false) PHP 官方手册说明:显然简 ...