繁体   English   中英

将FileInputStream的一部分写入FileOutPutstream

[英]Write part of FileInputStream into FileOutPutstream

我试图获取一个已录制的.wav文件,然后创建一个包含该wav文件的新输出流。 最终目标是让我拍波形,在特定点将其分割,然后在中间插入新音频。

我当时使用FFMPEG来执行此操作,但是FFMPEG的性能在最新版本的Android上已经变得非常糟糕。

我认为我最大的问题是缺乏对.read()和.write()方法的完全了解。

这是我尝试过的

final int SAMPLE_RATE = 44100; // Hz
final int ENCODING = AudioFormat.ENCODING_PCM_16BIT;
final int CHANNEL_MASK = AudioFormat.CHANNEL_IN_MONO;

in1 = new FileInputStream(Environment.getExternalStorageDirectory() + "/recording.wav");

out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/recording_part_1.wav");    

// Write out the wav file header
wavHeader.writeWavHeader(out, CHANNEL_MASK, SAMPLE_RATE, ENCODING);

while (in1.read(buffer, 0, buffer.length) != -1) {
           out.write(buffer);
}

out.close();
in1.close();

File fileToSave = new File(Environment.getExternalStorageDirectory() + "/GMT/recording_part_1.wav");

try {
    // This is not put in the try/catch/finally above since it needs to run
    // after we close the FileOutputStream
    wavHeader.updateWavHeader(fileToSave);
} catch (IOException ex) {

}

上面的作品,但它只是复制整个事情。 记录代码writeWaveHeader和updateWavHeader都来自这个要点https://gist.github.com/kmark/d8b1b01fb0d2febf5770

我已经尝试过类似的东西

for (int i = 0; i < in1.getChannel().size() / 2; i++) {
            out.write(in1.read(buffer, i, 1));
}

但这根本不起作用。 我也想

            byte[] byteInput = new byte[(int)in1.getChannel().size() - 44];
        while (in1.read(byteInput, 44, byteInput.length - 45) != -1) {
            out.write(byteInput, 44, byteInput.length /2);
        }

希望这只会创建一个包含一半文件的新文件。 我一直在看文档,但是做错了。

看看FileInputStream的文档

您的方法还不错。 这可以完成一些工作:

for (int i = 0; i < in1.getChannel().size() / 2; i++) {
    out.write(in1.read(buffer, i, 1));
}

医生说:

read(byte [] b,int off,int len) 从此输入流中最多将len个字节的数据读取到一个字节数组中。

您将缓冲区作为正确的byte []传递。

然后,您将i作为偏移量传递。 您的偏移量应为0 (因此从音频文件开始)。

对于len,您需要通过1。这应该是您要复制的长度。 因此,在那里传递in1.getChannel()。size()/ 2 (直到音频文件的中间)。

在这种情况下,您甚至不需要循环,因为read方法可以为您做所有事情。 要编辑零件的开始和结束,您需要更改2.&3。 参数。

因此,这应该为您工作:

 byte[] buffer = new byte[(int)(in1.gerChannel().size() / 2)];
 in1.read(buffer, 0, (int)(in1.gerChannel().size() / 2));
 out.write(buffer);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM