summaryrefslogtreecommitdiff
path: root/LoopbackApp/app/src/main/java/org/drrickorang/loopback/AudioFileOutput.java
blob: bc8343e19bf8b19285d5afdccfda25717ec7edbb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.drrickorang.loopback;

import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.File;
import android.net.Uri;
import android.content.Context;
import java.util.Arrays;

/**
 *
 */
public class AudioFileOutput {

    private static final String LOGTAG = "LoopbackWrite";
    private Uri mUri;
    private Context mContext;
    private FileOutputStream mOutputStream;
    private FileDescriptor mFileDescriptor;
    private int mSamplingRate = 48000;
    public AudioFileOutput(Context context, Uri uri, int samplingRate) {
        mContext = context;
        mUri = uri;
        mSamplingRate = samplingRate;
    }

    public boolean writeData(double [] data) {
        boolean status = false;
        ParcelFileDescriptor parcelFileDescriptor = null;
        try {
            parcelFileDescriptor =
                    mContext.getContentResolver().openFileDescriptor(mUri, "w");
            mFileDescriptor = parcelFileDescriptor.getFileDescriptor();
            mOutputStream = new FileOutputStream(mFileDescriptor);
            log("Done creating output stream");
            int sampleCount = data.length;
            writeHeader(sampleCount);
            writeDataBufer(data);
            mOutputStream.close();
            status = true;
            parcelFileDescriptor.close();
        } catch (Exception e) {
            mOutputStream = null;
            log("Failed to open wavefile" +e);
        } finally {
            try {
                if (parcelFileDescriptor != null) {
                    parcelFileDescriptor.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                log("Error closing ParcelFile Descriptor");
            }
        }
        return status;
    }

    private void writeHeader(int samples) {
        if (mOutputStream != null) {
            try {
                int channels = 1;
                int blockAlignment = 2;
                int bitsPerSample = 16;
                byte[] chunkSize = new byte[4];
                byte[] dataSize = new byte[4];
                int tempChunkSize =  samples*2 + 36;
                chunkSize[3] = (byte) (tempChunkSize >> 24);
                chunkSize[2] = (byte) (tempChunkSize >> 16);
                chunkSize[1] = (byte) (tempChunkSize >> 8);
                chunkSize[0] = (byte) tempChunkSize;
                int tempDataSize  = samples*2;
                dataSize[3] = (byte) (tempDataSize >> 24);
                dataSize[2] = (byte) (tempDataSize >> 16);
                dataSize[1] = (byte) (tempDataSize >> 8);
                dataSize[0] = (byte) tempDataSize;

                byte[] header = new byte[] {
                        'R', 'I', 'F', 'F',
                        chunkSize[0], chunkSize[1], chunkSize[2], chunkSize[3],
                        'W', 'A', 'V', 'E',
                        'f', 'm', 't', ' ',
                        16, 0, 0, 0,
                        1, 0,   // PCM
                        (byte) channels, 0,   // number of channels
                        (byte) mSamplingRate, (byte) (mSamplingRate >> 8), 0, 0,    // sample rate
                        0, 0, 0, 0, // byte rate
                        (byte) (channels * blockAlignment),
                        0,   // block alignment
                        (byte) bitsPerSample,
                        0,  // bits per sample
                        'd', 'a', 't', 'a',
                        dataSize[0], dataSize[1], dataSize[2], dataSize[3],
                };
                mOutputStream.write(header);
                log("Done writing header");
            } catch (IOException e) {
                Log.e(LOGTAG, "Error writing header "+e);
            }
        }
    }

    private void writeDataBufer(double [] data) {
        if (mOutputStream != null) {
            try {
                int sampleCount = data.length;
                int bufferSize = 1024; //blocks of 1024 samples
                byte [] buffer = new byte[bufferSize*2];
                double maxval = Math.pow(2, 15);
                for (int ii=0; ii<sampleCount; ii +=bufferSize) {
                    //clear buffer
                    Arrays.fill( buffer, (byte)0);
                    int bytesUsed =0;
                    for (int jj=0; jj<bufferSize; jj++) {
                        int index = ii+jj;
                        if (index>=sampleCount)
                            break;
                        int value = (int) Math.round( data[index]*maxval );
                        byte ba =(byte)( 0xFF &(value >>8));
                        byte bb = (byte) ( 0xFF &(value));
                        buffer[jj*2+1] = ba;
                        buffer[jj*2]   = bb;
                        bytesUsed +=2;
                    }
                    mOutputStream.write(buffer, 0, bytesUsed);
//                    log("writing samples:"+ii+"/"+ sampleCount);
                }
                log("Done writing data");
            } catch (IOException e) {
                Log.e(LOGTAG, "Error writing data "+e);
            }
        }
    }

    private static void log(String msg) {
        Log.v(LOGTAG, msg);
    }
}