android录制声音写入文件

来源:互联网 发布:sony vegas mac 编辑:程序博客网 时间:2024/06/05 10:45

android 通过mic录入声音,获取的是pcm(裸数据)格式的数据,可以使用(Auaacity 工具)打开能看语言的波形图,也能诊断回声消除;

1 使用API AudioRecord.read(short[] audioData, int offsetInShorts, int sizeInShorts),获取语言数据写入文件

现在获取的是short类型数据,需要把一个short 转化为2个字节的byte数组,若直接使用OutputStream.write(short  )会出现问题 

可以直接AudioRecord.read(byte[] audioData,int offsetInShorts, int sizeInShorts), 把byte 直接写入文件);       

        short 转化byte数组方法;

private void WriteShort(DataOutputStream bos, short s) throws IOException {

  byte[] mybyte = new byte[2];

  mybyte[1] =(byte)( (s << 16) >> 24 );

  mybyte[0] =(byte)( (s << 24) >> 24 );

  bos.write(mybyte);

}


然后OutputStream.write(byte[] buffer) 并OutputStream.flush();

2  可以把pcm 格式文件的数据.wav 使用播放器播放的音频格式:原理是在pcm文件head 加入.wav格式head 信息(网上可以搜到)

public void convertAudioFiles(Stringsrc, Stringtarget)throws Exception {

  FileInputStream fis = new FileInputStream(src);

  FileOutputStream fos = new FileOutputStream(target);


  //计算长度

  byte[] buf = new byte[1024 * 4];

  int size = fis.read(buf);

  int PCMSize = 0;

  while (size != -1) {

      PCMSize +=size;

      size =fis.read(buf);

    }

  fis.close();



  //填入参数,比特率等等。这里用的是16位单声道 8000hz

  WaveHeader header =new WaveHeader();

  //长度字段 = 内容的大小(PCMSize) + 头部字段的大小(不包括前面4字节的标识符RIFF以及fileLength本身的4字节)

  header.fileLength =PCMSize + (44 - 8);

  header.FmtHdrLeth = 16;

  header.BitsPerSample = 16;

  header.Channels = 1;

  header.FormatTag = 0x0001;

  header.SamplesPerSec = 8000;

  header.BlockAlign = (short)(header.Channels * header.BitsPerSample / 8);

  header.AvgBytesPerSec =header.BlockAlign *header.SamplesPerSec;

  header.DataHdrLeth =PCMSize;


  byte[] h = header.getHeader();


  asserth.length == 44;//WAV标准,头部应该是44字节

  //write header

  fos.write(h, 0,h.length);

  //write data stream

  fis = new FileInputStream(src);

  size = fis.read(buf);

  while (size != -1) {

      fos.write(buf, 0,size);

      size =fis.read(buf);

  }

  fis.close();

  fos.close();

  System.out.println("Convert OK!");

}




0 0