I need to convert .pcm to .wav file in my Android application. PCM audio recordings are raw digital audio samples. Previously, an PCM audio file was recorded with a sampling frequency of 16000, in single-channel mode(channelConfigurationRecord = AudioFormat.CHANNEL_IN_MONO), 16 bits in a sample(audioEncoding = AudioFormat.ENCODING_PCM_16BIT). To convert PCM to WAV, I need to write a header first and then just add all my PCM data. I spent a lot of time on this, I tried many variants and nothing works. I don't know what I'm doing wrong... Help me!
public class Convert {
File filePcm;
File fileWav;
char chunkId[]={'R','I','F','F'};
byte chunkSize[];
char format[]={'W','A','V','E'};
char subchunk1Id[]={'f','m','t',' '};
byte subchunk1Size[]={0b0,0b0,0b0,16};
byte audioFormat[]={0,1};
byte numChannels[]={0,1};
byte sampleRate[]={0b0,0b0,0b111110,(byte)0b10000000};
byte byteRate[]={0b0,0b0,0b1111101,0b0};
byte blockAlign[]={0,2};
byte bitsPerSample[]={0,16};
char subchunk2Id[]={'d','a','t','a'};
byte subchunk2Size[];
public Convert (File filePcm){
this.filePcm = filePcm;
}
public void convertWavFile(){
try {
fileWav = new File("");
fileWav.createNewFile();
writeHeader();
writePcmData();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeHeader() throws IOException {
long chunkSiz=36+filePcm.length();
chunkSize = new byte[]{ (byte) (chunkSiz & 0xff),
(byte) ((chunkSiz >> 8) & 0xff),
(byte) ((chunkSiz >> 16) & 0xff),
(byte) ((chunkSiz >> 24) & 0xff)};
long subchunk2Siz=filePcm.length();
subchunk2Size = new byte[]{ (byte) (subchunk2Siz & 0xff),
(byte) ((subchunk2Siz >> 8) & 0xff),
(byte) ((subchunk2Siz >> 16) & 0xff),
(byte) ((subchunk2Siz >> 24) & 0xff)};
FileOutputStream d = new FileOutputStream(fileWav);
for (char c:chunkId) d.write(c);
for (byte c:chunkSize) d.write(c);
for (char c:format) d.write(c);
for (char c:subchunk1Id) d.write(c);
for (byte c:subchunk1Size)d.write (c);
for (byte c:audioFormat)d.write (c);
for (byte c:numChannels)d.write (c);
for (byte c:sampleRate) d.write(c);
for (byte c:byteRate) d.write(c);
for (byte c:blockAlign)d.write (c);
for (byte c:bitsPerSample)d.write (c);
for (char c:subchunk2Id) d.write(c);
for (byte c:subchunk2Size) d.write(c);
}
private void writePcmData() throws IOException {
FileInputStream fileInputStream = new FileInputStream(filePcm);
FileOutputStream fileOutputStream = new FileOutputStream(fileWav);
int i;
while((i=fileInputStream.read())!=-1){
fileOutputStream.write(i);
}
}
}
the input data are pcm samples without processing, after creating and writing this shell the file is not recognized by any player
First of all add the FFMPEG library the library that make easy to convert ,merge ,mix videos and audios.
build.gradle(app)
Activity
Manifest
More Info