最近项目遇到了音频处理的问题,找了很久没找到合适android用的,最后改动了一下某位大佬的代码,放到项目里还是能用的,记录一下/*** 开始裁剪** @param start 开始时间(毫秒)* @param end 结束时间(毫秒)* <p>* return 截取成功返回true,否则返回false*/
public static boolean cut(String sourcefile, String targetfile, int start, int end) {try {if (!sourcefile.toLowerCase().endsWith(".wav") || !targetfile.toLowerCase().endsWith(".wav")) {return false;}File wav = new File(sourcefile);if (!wav.exists()) {return false;}long t1 = getWavLength(wav); //总时长(秒)if (start < 0 || end <= 0 || start >= t1 || end > t1 || start >= end) {return false;}FileInputStream fis = new FileInputStream(wav);long wavSize = wav.length() - 44; //音频数据大小(44为128kbps比特率wav文件头长度)long splitSize = (wavSize / t1) * (end - start); //截取的音频数据大小long skipSize = (wavSize / t1) * start; //截取时跳过的音频数据大小int splitSizeInt = Integer.parseInt(String.valueOf(splitSize));int skipSizeInt = Integer.parseInt(String.valueOf(skipSize));ByteBuffer buf1 = ByteBuffer.allocate(4); //存放文件大小,4代表一个int占用字节数buf1.putInt(splitSizeInt + 36); //放入文件长度信息byte[] flen = buf1.array(); //代表文件长度ByteBuffer buf2 = ByteBuffer.allocate(4); //存放音频数据大小,4代表一个int占用字节数buf2.putInt(splitSizeInt); //放入数据长度信息byte[] dlen = buf2.array(); //代表数据长度flen = reverse(flen); //数组反转dlen = reverse(dlen);byte[] head = new byte[44]; //定义wav头部信息数组fis.read(head, 0, head.length); //读取源wav文件头部信息for (int i = 0; i < 4; i++) { //4代表一个int占用字节数head[i + 4] = flen[i]; //替换原头部信息里的文件长度head[i + 40] = dlen[i]; //替换原头部信息里的数据长度}byte[] fbyte = new byte[splitSizeInt + head.length]; //存放截取的音频数据for (int i = 0; i < head.length; i++) { //放入修改后的头部信息fbyte[i] = head[i];}byte[] skipBytes = new byte[skipSizeInt]; //存放截取时跳过的音频数据fis.read(skipBytes, 0, skipBytes.length); //跳过不需要截取的数据fis.read(fbyte, head.length, fbyte.length - head.length); //读取要截取的数据到目标数组fis.close();File target = new File(targetfile);if (target.exists()) { //如果目标文件已存在,则删除目标文件target.delete();}FileOutputStream fos = new FileOutputStream(target);fos.write(fbyte);fos.flush();fos.close();} catch (IOException e) {e.printStackTrace();return false;}return true;
}/*** 根据MediaPlayer获取wav音频时长 ms** @return*/
public static long getWavLength(File file) {MediaPlayer player = new MediaPlayer();try {player.setDataSource(file.getPath()); //recordingFilePath()为音频文件的路径player.prepare();} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}long duration = player.getDuration();//获取音频的时间Log.d("ACETEST", "### duration: " + duration);player.release();//记得释放资源return duration;
}/*** 数组反转** @param array*/
public static byte[] reverse(byte[] array) {byte temp;int len = array.length;for (int i = 0; i < len / 2; i++) {temp = array[i];array[i] = array[len - 1 - i];array[len - 1 - i] = temp;}return array;
}
最后如果有兴趣的可以关注一下我的公众号吧,虽然很菜,但是还是渴望成长