2
votes

I realized after going through a post in the IBM developer forums that the android sdk reads bytes from the mic recording and writes them to the websocket. I am now trying to read bytes from an audio file on memory and write them to the websocket. How should I do this? So far I have:

public class AudioCaptureThread extends Thread{

private static final String TAG = "AudioCaptureThread";
private boolean mStop = false;
private boolean mStopped = false;
private int mSamplingRate = -1;
private IAudioConsumer mIAudioConsumer = null;

// the thread receives high priority because it needs to do real time audio capture
// THREAD_PRIORITY_URGENT_AUDIO = "Standard priority of the most important audio threads"
public AudioCaptureThread(int iSamplingRate, IAudioConsumer IAudioConsumer) {
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
    mSamplingRate = iSamplingRate;
    mIAudioConsumer = IAudioConsumer;
}

// once the thread is started it runs nonstop until it is stopped from the outside
@Override
public void run() {

    File path = Activity.getContext.getExternalFilesDir(null);
    File file = new File (path, "whatstheweatherlike.wav");
    int length = (int) file.length();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[length];
    FileInputStream in = null;
    try {
        in = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        for (int readNum; (readNum = in.read(b)) != -1;) {
            bos.write(b, 0, readNum);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    byte[] bytes = bos.toByteArray();
    mIAudioConsumer.consume(bytes);
}

However, Activity.getContext is not recognized. I can convert the file to bytes in MainActivity but how do I then write it to the websocket? Am I on the right track or is this not the right way? If it is, how do I solve this problem?

Any help is appreciated!

1

1 Answers

2
votes

Activity.getContext is not recognized because there's no reference to Activity, since it's just a Thread. You would have to pass in the Activity, although it would likely make more sense just to pass in the Context if you need it.

You've got the right idea that you can create a FileInputStream and use that. You might like to use our MicrophoneCaptureThread as a reference. It'd be a very similar situation, except you'd be using your FileInputStream instead of reading from the microphone. You can check it out (and an example project that uses it) here: https://github.com/watson-developer-cloud/android-sdk/blob/master/library/src/main/java/com/ibm/watson/developer_cloud/android/library/audio/MicrophoneCaptureThread.java