Search code examples
androidandroid-audiomanagerandroid-audiorecord

Android Activity Will not Playback Recording


I am trying to make an recording in one activity and then play it back in another activity. I have no trouble doing this if it is in the same activity. When I split it, I can't seem to get it to work out at all. Everything is the same, just split, so I assume it cant find the path to the file saved on the phone. Please help!!!

This is the first activity where the recording takes place:

public class RecorderActivity2 extends Activity {

    MediaRecorder recorder = null; //Recorder object used to record the audio tone
    String path = null; //Stores the path of the media files that is been recorded
    TextView title_text;
    //How long the Recording lasts
    int timer = 10000;
    String log_tag = "Recorder1";
    //DELAY AFTER THE RECORDING IS COMPLETED
    int delay = 10000;
    String file;
    Context mContext;
    Handler mHandler = new Handler();
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

                /*
         * API's to launch the application when the tablet is locked or
         * display is turned off
         */
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
        setContentView(R.layout.activity_recorder);


        //Check to see if the device has a microphone
        PackageManager pm = getPackageManager();
        boolean micPresent = pm.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
        boolean playerPresent = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT);
        if (!micPresent){
            Log.i(log_tag, "There is no microphone present in this device.");
            exit_function();
        }
        else {

            createTempFile("Status_Recorder.txt", "INPROGRESS");

        /*
          * Create the file where the audio tone that is recorded will be saved
          *
          */
            path = getApplicationContext().getFilesDir().getAbsolutePath() + "/audio_test.3gp";
            try {
                FileOutputStream fOut = openFileOutput("audio_test.3gp", MODE_WORLD_READABLE);
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(log_tag, "FAILED TO CREATE THE FILE OUTPUT STREAM");
                exit_function();
            }



            start_recording();
        }
    }

    //Method to Start the Recording
    private void start_recording() {
        if (recorder != null) {
            recorder.release();
        }
        //Setting for the Recorder
        try{
            Log.i(log_tag,"Setting the recorder");
            // MediaRecorder.
            recorder = new MediaRecorder();
            recorder.reset();
            //audioManager.setMicrophoneMute(false);
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

        } catch(Exception e){
            Log.e(log_tag,"Recording Settings Failed");
            createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
            exit_function();
        }
        //Prepare the Recorder
        try{
            Log.i(log_tag,"Preparing the Recorder");
            recorder.prepare();
        } catch(Exception e){
            Log.e(log_tag,"Recording failed");
            createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
            exit_function();
        }

        //Start the Recorder
        try {
            Log.i(log_tag,"Starting the recorder");
            title_text = ((TextView) findViewById(R.id.textView));
            title_text.setTextColor(Color.RED);
            title_text.setText("RECORDING");
            recorder.start();

            //The recording lasts as long as he timer and then stops
            mHandler.postDelayed(new Runnable() {
                public void run() {
                    if (recorder != null) {
                        recorder.stop();
                        recorder.reset();
                        recorder.release();
                        recorder = null;
                    }
                    Log.e(log_tag,"First Delay");
                    exit_function();
                }
            }, 5000);
            createTempFile("Status_Recorder.txt", "Complete");

            //This Delay is between Recording and Playback
            mHandler.postDelayed(new Runnable() {
                public void run() {
                }
            }, 5000);

        } catch (Exception e) {
            Log.e(log_tag,"Recorder start failed");
            createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
            exit_function();
        }

    }




    private void exit_function() {

        onDestroy();
    }

    @Override
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     * Function invoked before we exit the application . Reset all the volume
     * and stream values in this function
     */
    protected void onDestroy() {
        Log.i(log_tag,"Entered onDestroy()");
        super.onDestroy();
        if (recorder != null) {
            recorder.release();
        }
        this.finish();

    }

    /*
     * Function to create the a text file in the application directory context. This function
     * takes the file name and the string that is to be written in it as the input. This function is invoked
     * to create the Result.txt file.
     */
    private void createTempFile(String filename, String text) {

        try {
            FileOutputStream fOut = openFileOutput(filename , MODE_WORLD_READABLE);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            osw.write(text);
            osw.flush();
            osw.close();

        } catch(IOException e) {
            e.printStackTrace();
        }

    }


}

This is from the Second Recording that plays back the recording:

public class RecorderPlaybackActivity extends Activity {

    int default_mode; //Saves the default mode of the device
    int music_volume; //Saves the default volume of the music stream
    int call_volume; //Saves the default volume of the in call stream
    AudioManager audioManager = null; //Object to provide access to system volume controls and settings
    MediaPlayer mPlayer = null; //Media object which has the playback control of audio and video files
    String path = null; //Stores the path of the media files that is been recorded
    TextView title_text;
    //How long the Recording lasts
    int timer = 10000;
    String log_tag = "RecorderPlayback";
    //DELAY AFTER THE RECORDING IS COMPLETED
    String file;
    final static int FOR_MEDIA = 1;
    final static int FORCE_NONE = 0;
    final static int FORCE_SPEAKER = 1;
    Class audioSystemClass = null;
    Method setForceUse = null;
    int volume = 20;
    Context mContext;
    Handler mHandler = new Handler();
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

                /*
         * API's to launch the application when the tablet is locked or
         * display is turned off
         */
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
        setContentView(R.layout.activity_recorder);

        //Check to see if the device supports audio output
        PackageManager pm = getPackageManager();
        boolean playerPresent = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT);
        if (!playerPresent){
            Log.i(log_tag, "There is no audio player present in this device.");
            exit_function();
        }
        else {

            createTempFile("Status_Recorder.txt", "INPROGRESS");

        /*
          * Create the file where the audio tone that is recorded will be saved
          *
          */
            try {
                FileOutputStream fOut = openFileOutput("audio_test.3gp", MODE_WORLD_READABLE);
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(log_tag, "FAILED TO CREATE THE FILE OUTPUT STREAM");
                exit_function();
            }
            path = getApplicationContext().getFilesDir().getAbsolutePath() + "/audio_test.3gp";

            audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
            default_mode = audioManager.getMode();
            music_volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            call_volume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);

//        //Setting the volume level
//        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
//        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,volume, AudioManager.FLAG_SHOW_UI);

            //Setting the volume to max
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);


            try {
                audioSystemClass = Class.forName("android.media.AudioSystem");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            try {
                setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            try {
                setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }


            start_playback();
        }

    }

    public void start_playback() {

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }

        mPlayer = new MediaPlayer();
        //Setting the playback path
        try {
            Log.i(log_tag, "setting the data source");
            mPlayer.setDataSource(path); //The variable path contains the file path where the recorded tone was saved

        } catch (Exception e) {
            Log.e(log_tag, "exception while setting the data source");
            createTempFile("Status.txt", "COMPLETED-PLAYER FAILED");
            exit_function();
        }

        //Preparing the playback
        try {
            mPlayer.prepare();
        } catch (Exception e) {
            Log.e(log_tag, "prepare() failed");
            createTempFile("Status.txt", "COMPLETED-PLAYER FAILED");
            exit_function();
        }
        //Playing the recording
        try {
            Log.i(log_tag, "starting the audio playback # " + (count+1));
            title_text.setText("PLAYING RECORDING #" + (count+1));
            audioManager.setSpeakerphoneOn(true);
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.start();
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mPlayer) {

                    //Change this delay for break in between playback
                    mHandler.postDelayed(new Runnable() {
                        public void run() {

                            if (count <1){
                                count++;
                                start_playback();

                            }

                            else{
                                createTempFile("Status_Recorder.txt", "COMPLETED");
                                exit_function();
                            }
                        }
                    }, 0);
                }
            });
        } catch (Exception e) {
            Log.e(log_tag, "start failed");
            createTempFile("Status.txt", "COMPLETED-PLAYER FAILED");
            exit_function();
        }
    }




    private void exit_function() {

        onDestroy();
    }

    @Override
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     * Function invoked before we exit the application . Reset all the volume
     * and stream values in this function
     */
    protected void onDestroy() {
        Log.i(log_tag,"Entered onDestroy()");
        super.onDestroy();
        if (mPlayer != null) {
            mPlayer.release();
        }
        //Reset to the default settings here
        audioManager.setMode(default_mode);
        try {
            setForceUse.invoke(null, FOR_MEDIA, FORCE_NONE);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, music_volume, 0);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, call_volume, 0);
        this.finish();


    }

    /*
     * Function to create the a text file in the application directory context. This function
     * takes the file name and the string that is to be written in it as the input. This function is invoked
     * to create the Result.txt file.
     */
    private void createTempFile(String filename, String text) {

        try {
            FileOutputStream fOut = openFileOutput(filename , MODE_WORLD_READABLE);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            osw.write(text);
            osw.flush();
            osw.close();

        } catch(IOException e) {
            e.printStackTrace();
        }

    }


}

Solution

  • I was able to finally figure out what I was doing wrong. I had the following line at the top of both activities:

        //Create the file that will be used to save the recording
        try {
            FileOutputStream fOut = openFileOutput("audio_test.3gp", MODE_WORLD_READABLE);
    
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(log_tag, "FAILED TO CREATE THE FILE OUTPUT STREAM");
            exit_function();
        }