Java 音频处理,音频流转音频文件,获取音频播放时长

35 篇文章 1 订阅
22 篇文章 2 订阅

1.背景

最近对接了一款智能手表,手环,可以应用与老人与儿童监控,环卫工人监控,农场畜牧业监控,宠物监控等,其中用到了音频传输,通过平台下发语音包,发送远程命令录制当前设备音频并将音频分包传输到服务器上生成音频文件等。其中关于音频的一些简单操作封装成了工具包。

2.音频工具包

引入jaudiotagger,用来获取MP3格式的音频时长。

        <dependency>
            <groupId>org</groupId>
            <artifactId>jaudiotagger</artifactId>
            <version>2.0.1</version>
        </dependency>

工具包代码:AudioUtils
 

package com.xxxx.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 音频处理工具类
 * @author Mr.Li
 * @date 2023-10-26
 */
@Slf4j
public class AudioUtils {
    /**
     * 二进制流转音频文件
     * @param binaryData
     * @param outputFilePath
     * @throws IOException
     */
    public static boolean convertBinaryToAudio(byte[] binaryData, String outputFilePath) throws IOException {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(outputFilePath);
            outputStream.write(binaryData);
            return true;
        }catch (Exception e){
            log.error("convertBinaryToAudio:outputFilePath:{}",outputFilePath,e);
            return false;
        }finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
    /**
     * 获取AMR格式音频长度
     * @param file
     * @return
     * @throws IOException
     */
    public static int getAmrDuration(File file) throws IOException {
        long duration = -1;
        int[] packedSize = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0,
                0, 0 };
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");
            // 文件的长度
            long length = file.length();
            // 设置初始位置
            int pos = 6;
            // 初始帧数
            int frameCount = 0;
            int packedPos = -1;
            // 初始数据值
            byte[] datas = new byte[1];
            while (pos <= length) {
                randomAccessFile.seek(pos);
                if (randomAccessFile.read(datas, 0, 1) != 1) {
                    duration = length > 0 ? ((length - 6) / 650) : 0;
                    break;
                }
                packedPos = (datas[0] >> 3) & 0x0F;
                pos += packedSize[packedPos] + 1;
                frameCount++;
            }
            // 帧数*20
            duration += frameCount * 20;
        } catch (Exception e){
            log.error("getAmrDuration:",e);
        }finally {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        }
        return (int)((duration/1000)+1);
    }

    /**
     * 计算Mp3音频格式时长
     * @param mp3File
     * @return
     */
    public static int getMp3Duration(File mp3File) {
        try {
            MP3File f = (MP3File) AudioFileIO.read(mp3File);
            MP3AudioHeader audioHeader = (MP3AudioHeader) f.getAudioHeader();
            return audioHeader.getTrackLength();
        } catch (Exception e) {
            log.error("getMp3Duration:",e);
            return 0;
        }
    }

    public static void main(String[] args) throws IOException {
        String path="C:\\Users\\MyPC\\Desktop\\卡布奇诺-王逗逗.mp3";
        int duration = getMp3Duration(new File(path));
        System.out.println(duration);
    }
}

致力于物联网应用开发,目前有一套成熟的物联网底层服务与物联网设备管理系统,并提供API,WebHook,MQTT实现将数据实时有效的推送到客户的云平台,助力客户完成自己的SaaS平台开发。

欢迎对物联网感兴趣的朋友加我微信交流学习。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在Java处理音频特征向量,你可以使用音频处理库,如TarsosDSP或Librosa等,这些库提供了许多功能和算法,用于处理音频特征向量。下面是一个使用TarsosDSP库实现处理音频特征向量的示例代码: ```java import be.tarsos.dsp.AudioDispatcher; import be.tarsos.dsp.AudioEvent; import be.tarsos.dsp.AudioProcessor; import be.tarsos.dsp.io.TarsosDSPAudioInputStream; import be.tarsos.dsp.io.jvm.JVMAudioInputStream; import be.tarsos.dsp.mfcc.MFCC; import javax.sound.sampled.*; import java.io.File; import java.io.IOException; public class AudioFeatureProcessing { public static void main(String[] args) { String audioFile = "audio.wav"; // 读取音频文件 File file = new File(audioFile); AudioInputStream audioStream; try { audioStream = AudioSystem.getAudioInputStream(file); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); return; } // 将音频流转换为TarsosDSP需要的格式 TarsosDSPAudioInputStream audioInputStream = new JVMAudioInputStream(audioStream); // 创建MFCC对象 int sampleRate = (int) audioInputStream.getFormat().getSampleRate(); int bufferSize = 1024; // 缓冲区大小 int bufferOverlap = 0; // 缓冲区重叠大小 int mfccCoefficients = 13; // MFCC系数数量 MFCC mfcc = new MFCC(bufferSize, sampleRate, mfccCoefficients, 40, 300, 133.3334f, 22050.0f); // 创建AudioDispatcher对象并注册处理器 AudioDispatcher dispatcher = new AudioDispatcher(audioInputStream, bufferSize, bufferOverlap); dispatcher.addAudioProcessor(new AudioProcessor() { @Override public boolean process(AudioEvent audioEvent) { float[] audioBuffer = audioEvent.getFloatBuffer(); // 计算MFCC特征向量 mfcc.process(audioBuffer); double[] featureVector = mfcc.getMFCC(); // 处理特征向量 processFeatureVector(featureVector); return true; } @Override public void processingFinished() { // 处理完成回调 } }); // 启动处理 dispatcher.run(); } public static void processFeatureVector(double[] featureVector) { // 处理特征向量 // ... } } ``` 上述代码使用TarsosDSP库将音频文件转换为TarsosDSP所需的格式,并通过MFCC(Mel Frequency Cepstral Coefficients)算法计算MFCC特征向量。你可以根据实际需求选择合适的特征提取方法和处理方式。请注意,上述代码只是演示了大致的实现思路,具体的特征提取和处理方法需要根据实际情况进行选择和实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鱼>

一分也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值