PCM音频数据调节音量大小

2019-12-02  本文已影响0人  woo_5857

来源 https://www.jianshu.com/p/50c697bec409

1.前言

最近项目里面有段音频流需要代码控制音量大小,之前是直接推到服务器端用于语音识别的,由于多设备同时在运行,会存在串音的问题,因此各设备在设置页都增加了一个可滑动进度条,用于动态调解音频流音量的大小。

2.遇到问题

虽然之前并未接触过类似的知识点,但在网上找到了pcm音量控制这篇文章,文章看起来很高大上,不过我们需要用到的好像就是一个公式而已:

就是这么个东西,具体解释大家可以点击上面的文章链接看看原理,其中 A1 和 A2 是两个声音的振幅,此处的A2为原始音频振幅,A1为根据所指定db大小计算出来的调节音量后的音频振幅,画不多说,试试效果:

intdb= -4;

privatedoublefactor= Math.pow(10,db /20);

//调节PCM数据音量

//pData原始音频byte数组,nLen原始音频byte数组长度,data2转换后新音频byte数组,nBitsPerSample采样率,multiple表示Math.pow()返回值

publicintamplifyPCMData(byte[] pData,intnLen, byte[] data2,intnBitsPerSample,floatmultiple)

{

    intnCur =0;

    if(16== nBitsPerSample)

    {

        while(nCur < nLen)

        {

            shortvolum = getShort(pData, nCur);

            volum = (short)(volum * multiple);

            data2[nCur]  = (byte)( volum      &0xFF);

            data2[nCur+1] = (byte)((volum >>8) &0xFF);

            nCur +=2;

        }

    }

    return0;

}

privateshortgetShort(byte[] data,intstart)

{

    return(short)((data[start] &0xFF) | (data[start+1] <<8));

}

//把音频byte[]写入本地文件

publicstaticvoidbyte2file(String pathName, byte[] data) {

    BufferedOutputStream bos = null;

    File file = null;

    try {

        File dir = new File(Environment.getExternalStorageDirectory() +"/test/");

        if(!dir.exists()) {//判断文件目录是否存在

            dir.mkdirs();

        }

        file = new File(Environment.getExternalStorageDirectory() +"/test/"+ pathName);

        /* 使用以下2行代码时,不追加方式*/

        /*bos = new BufferedOutputStream(new FileOutputStream(file));

        bos.write(bfile); */

        /* 使用以下3行代码时,追加方式*/

        bos = new BufferedOutputStream(new FileOutputStream(file,true));

        bos.write(data);

        bos.flush();

    } catch (Exception e) {

        e.printStackTrace();

    } finally {

        if(bos != null) {

            try {

                bos.close();

            } catch (IOException e1) {

                e1.printStackTrace();

            }

        }

    }

}

上一篇 下一篇

猜你喜欢

热点阅读