Example usage for android.media MediaRecorder MediaRecorder

List of usage examples for android.media MediaRecorder MediaRecorder

Introduction

In this page you can find the example usage for android.media MediaRecorder MediaRecorder.

Prototype

public MediaRecorder() 

Source Link

Document

Default constructor.

Usage

From source file:net.kidlogger.kidlogger.KLService.java

public void startRecord(final String callType, final String callNumber) {
    //Log.i("KLS", "startRecord");
    new Thread(new Runnable() {
        public void run() {
            String rootDir = Environment.getExternalStorageDirectory().getAbsolutePath();
            String path = rootDir + "/.callrecords/" + getDateString();
            String name = new String();
            String tmp = getNameFromContacts(callNumber, true);
            if (tmp.equals("unknown"))
                name = sanityNumber(callNumber) + "_";
            else//from w w  w  . j  av  a 2  s.c o  m
                name = sanityNumber(tmp) + "_";

            recFile = new File(path, callType + name + getTimeString() + ".3gp");

            File directory = recFile.getParentFile();
            //Log.i("KLS", "Audio: " + recFile.getName());
            String state = Environment.getExternalStorageState();

            if (!state.equals(Environment.MEDIA_MOUNTED))
                return;

            if (!directory.exists())
                directory.mkdirs();

            recording = true;
            // Initialize recorder
            recorder = new MediaRecorder();
            try {
                recorder.setAudioSource(AudioSource.VOICE_UPLINK);
                recorder.setOutputFormat(OutputFormat.THREE_GPP);
                recorder.setAudioEncoder(AudioEncoder.DEFAULT);
                recorder.setOutputFile(recFile.getAbsolutePath());
                recorder.setMaxDuration(Settings.getMaxTimeRec(KLService.this));
                recorder.setMaxFileSize(Settings.getMaxSizeRec(KLService.this));
                recorder.setOnInfoListener(new MediaInfoListener());
                recorder.prepare();
                recorder.start();
            } catch (IllegalStateException e) {
                recording = false;
                app.logError("AudioRecordThread", e.toString());
            } catch (IOException e) {
                recording = false;
                app.logError("AudioRecordThread", e.toString());
            }
        }
    }).start();

    // Start recording
    /*new Thread(new Runnable(){
       public void run(){
    recording = true;
    // Initialize recorder
    recorder = new MediaRecorder();
    try{
       recorder.setAudioSource(AudioSource.VOICE_UPLINK);
       recorder.setOutputFormat(OutputFormat.THREE_GPP);
       recorder.setAudioEncoder(AudioEncoder.AMR_NB);
       recorder.setOutputFile(recFile.getAbsolutePath());
       recorder.setMaxDuration(Settings.getMaxTimeRec(KLService.this));
       recorder.setMaxFileSize(Settings.getMaxSizeRec(KLService.this));
       recorder.setOnInfoListener(new MediaInfoListener());
       recorder.prepare();
       recorder.start();
    }catch(IllegalStateException e){
       recording = false;
       app.logError("AudioRecordThread", e.toString());
    }catch(IOException e){
       recording = false;
       app.logError("AudioRecordThread", e.toString());
    }
       }
    }).start();*/

    /*AudioRecordThread art = new AudioRecordThread("record", recFile);
    try{
       art.t.join();
    }catch(InterruptedException e){
       app.logError(CN + "startRecord", e.toString());
    }*/
}

From source file:org.telegram.ui.ChatActivity.java

private void startRecording() {
    if (audioRecorder != null) {
        return;//w ww  .  j a v a  2  s  . c  o  m
    }

    recordingAudio = new TLRPC.TL_audio();
    recordingAudio.dc_id = Integer.MIN_VALUE;
    recordingAudio.id = UserConfig.lastLocalId;
    recordingAudio.user_id = UserConfig.clientUserId;
    UserConfig.lastLocalId--;
    UserConfig.saveConfig(false);

    recordingAudioFile = new File(Utilities.getCacheDir(), MessageObject.getAttachFileName(recordingAudio));

    audioRecorder = new MediaRecorder();
    audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    audioRecorder.setOutputFile(recordingAudioFile.getAbsolutePath());
    if (android.os.Build.VERSION.SDK_INT >= 10) {
        audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    } else {
        audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    }
    audioRecorder.setAudioSamplingRate(24000);
    audioRecorder.setAudioChannels(1);
    audioRecorder.setAudioEncodingBitRate(16000);

    try {
        audioRecorder.prepare();
        audioRecorder.start();
    } catch (Exception e) {
        Log.e("tmessages", "prepare() failed");
    }
}

From source file:it.feio.android.omninotes.DetailFragment.java

private void startRecording(View v) {
    PermissionsHelper.requestPermission(getActivity(), Manifest.permission.RECORD_AUDIO,
            R.string.permission_audio_recording, snackBarPlaceholder, () -> {

                isRecording = true;/*www  .ja  v a  2s  . c  o  m*/
                android.widget.TextView mTextView = (android.widget.TextView) v;
                mTextView.setText(getString(R.string.stop));
                mTextView.setTextColor(Color.parseColor("#ff0000"));

                File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_AUDIO_EXT);
                if (f == null) {
                    mainActivity.showMessage(R.string.error, ONStyle.ALERT);
                    return;
                }
                if (mRecorder == null) {
                    mRecorder = new MediaRecorder();
                    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                    mRecorder.setAudioEncodingBitRate(96000);
                    mRecorder.setAudioSamplingRate(44100);
                }
                recordName = f.getAbsolutePath();
                mRecorder.setOutputFile(recordName);

                try {
                    audioRecordingTimeStart = Calendar.getInstance().getTimeInMillis();
                    mRecorder.prepare();
                    mRecorder.start();
                } catch (IOException | IllegalStateException e) {
                    Log.e(Constants.TAG, "prepare() failed", e);
                    mainActivity.showMessage(R.string.error, ONStyle.ALERT);
                }
            });
}

From source file:com.dycody.android.idealnote.DetailFragment.java

private void startRecording(View v) {
    PermissionsHelper.requestPermission(getActivity(), Manifest.permission.RECORD_AUDIO,
            R.string.permission_audio_recording, snackBarPlaceholder, () -> {

                isRecording = true;//from  www  .j  av  a 2  s . c om
                android.widget.TextView mTextView = (android.widget.TextView) v;
                mTextView.setText(getString(R.string.stop));
                mTextView.setTextColor(Color.parseColor("#ff0000"));

                File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_AUDIO_EXT);
                if (f == null) {
                    Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_SHORT).show();
                    //mainActivity.showMessage(R.string.error, ONStyle.ALERT);
                    return;
                }
                if (mRecorder == null) {
                    mRecorder = new MediaRecorder();
                    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                    mRecorder.setAudioEncodingBitRate(96000);
                    mRecorder.setAudioSamplingRate(44100);
                }
                recordName = f.getAbsolutePath();
                mRecorder.setOutputFile(recordName);

                try {
                    audioRecordingTimeStart = Calendar.getInstance().getTimeInMillis();
                    mRecorder.prepare();
                    mRecorder.start();
                } catch (IOException | IllegalStateException e) {
                    Log.e(Constants.TAG, "prepare() failed", e);
                    Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_SHORT).show();
                    //mainActivity.showMessage(R.string.error, ONStyle.ALERT);
                }
            });
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

private void startRecording() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
    //get current date time with Date()
    Date date = new Date();
    String customDate = dateFormat.format(date);

    File myDataPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Recordings");
    if (!myDataPath.exists())
        myDataPath.mkdir();//  w  ww .  j ava  2  s.  c  o m

    audiofile = new File(myDataPath + "/" + customDate + ".3gp");
    /* mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
     mFileName +=  "/" + customDate + ".3gp";
            
    // String mfileName = mFileName + customDate + ".3gp";
    // File newFile = new File(dir, fileName);*/

    mRecorder = new MediaRecorder();
    mRecorder.setMaxDuration(30000);
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setOutputFile(audiofile.getAbsolutePath());
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e(TAG, "prepare() failed");
    }

    mRecorder.start();
}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public Media createMediaRecorder(final String path, final String mimeType) throws IOException {
    if (getActivity() == null) {
        return null;
    }// w  w w  . jav a  2 s  .co  m
    if (!checkForPermission(Manifest.permission.RECORD_AUDIO, "This is required to record audio")) {
        return null;
    }
    final AndroidRecorder[] record = new AndroidRecorder[1];
    final IOException[] error = new IOException[1];

    final Object lock = new Object();
    synchronized (lock) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    MediaRecorder recorder = new MediaRecorder();
                    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    if (mimeType.contains("amr")) {
                        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
                        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    } else {
                        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                    }
                    recorder.setOutputFile(removeFilePrefix(path));
                    try {
                        recorder.prepare();
                        record[0] = new AndroidRecorder(recorder);
                    } catch (IllegalStateException ex) {
                        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        error[0] = ex;
                    } finally {
                        lock.notify();
                    }

                }
            }
        });

        try {
            lock.wait();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        if (error[0] != null) {
            throw error[0];
        }

        return record[0];
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public void captureAudio(final ActionListener response) {

    if (!checkForPermission(Manifest.permission.RECORD_AUDIO, "This is required to record the audio")) {
        return;/*from   w w  w .j  av  a  2 s  . c o m*/
    }

    try {
        final Form current = Display.getInstance().getCurrent();

        final File temp = File.createTempFile("mtmp", ".3gpp");
        temp.deleteOnExit();

        if (recorder != null) {
            recorder.release();
        }
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
        recorder.setOutputFile(temp.getAbsolutePath());

        final Form recording = new Form("Recording");
        recording.setTransitionInAnimator(CommonTransitions.createEmpty());
        recording.setTransitionOutAnimator(CommonTransitions.createEmpty());
        recording.setLayout(new BorderLayout());

        recorder.prepare();
        recorder.start();

        final Label time = new Label("00:00");
        time.getAllStyles().setAlignment(Component.CENTER);
        Font f = Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE);
        f = f.derive(getDisplayHeight() / 10, Font.STYLE_PLAIN);
        time.getAllStyles().setFont(f);
        recording.addComponent(BorderLayout.CENTER, time);

        recording.registerAnimated(new Animation() {

            long current = System.currentTimeMillis();
            long zero = current;
            int sec = 0;

            public boolean animate() {
                long now = System.currentTimeMillis();
                if (now - current > 1000) {
                    current = now;
                    sec++;
                    return true;
                }
                return false;
            }

            public void paint(Graphics g) {
                int seconds = sec % 60;
                int minutes = sec / 60;

                String secStr = seconds < 10 ? "0" + seconds : "" + seconds;
                String minStr = minutes < 10 ? "0" + minutes : "" + minutes;

                String txt = minStr + ":" + secStr;
                time.setText(txt);
            }
        });

        Container south = new Container(new com.codename1.ui.layouts.GridLayout(1, 2));
        Command cancel = new Command("Cancel") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                if (recorder != null) {
                    recorder.stop();
                    recorder.release();
                    recorder = null;
                }
                current.showBack();
                response.actionPerformed(null);
            }

        };
        recording.setBackCommand(cancel);
        south.add(new com.codename1.ui.Button(cancel));
        south.add(new com.codename1.ui.Button(new Command("Save") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                if (recorder != null) {
                    recorder.stop();
                    recorder.release();
                    recorder = null;
                }
                current.showBack();
                response.actionPerformed(new ActionEvent(temp.getAbsolutePath()));
            }

        }));
        recording.addComponent(BorderLayout.SOUTH, south);
        recording.show();

    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException("failed to start audio recording");
    }

}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

@Override
public boolean onTouch(View v, MotionEvent event) {

    int action = event.getActionMasked();
    switch (v.getId()) {
    case R.id.record_audio:
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            textRecordingPress.setVisibility(View.INVISIBLE);
            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
            fechaAudioMillis = Calendar.getInstance().getTimeInMillis();
            File directory = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent");
            directory.mkdirs();/* w w  w  .  j av a 2  s  .  co m*/
            ficheroAudio = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent/"
                    + fechaAudioMillis + ".mp4";
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setOutputFile(ficheroAudio);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            try {
                mediaRecorder.prepare();
            } catch (IOException e) {
            }
            mediaRecorder.start();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    finalTime += 1000;
                    int seconds = (int) (finalTime / 1000) % 60;
                    int minutes = (int) ((finalTime / (1000 * 60)) % 60);
                    int hours = (int) ((finalTime / (1000 * 60 * 60)) % 24);
                    timeFinal = String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
                    timerAudio.setText(timeFinal);
                    if (!saveAudio) {
                        textRecording.setText(timeFinal);
                    }
                    handler.postDelayed(this, 1000);
                }
            });
            scaleAnimX = ObjectAnimator.ofFloat(recordAudioButton, "scaleX", 1, 1.2f);
            scaleAnimX.setDuration(800);
            scaleAnimX.setRepeatCount(ValueAnimator.INFINITE);
            scaleAnimX.setRepeatMode(ValueAnimator.REVERSE);
            scaleAnimY = ObjectAnimator.ofFloat(recordAudioButton, "scaleY", 1, 1.2f);
            scaleAnimY.setDuration(800);
            scaleAnimY.setRepeatCount(ValueAnimator.INFINITE);
            scaleAnimY.setRepeatMode(ValueAnimator.REVERSE);
            scaleAnimY.start();
            scaleAnimX.start();

            scaleRedBackgroundX = ObjectAnimator.ofFloat(audioRecordBackground, "scaleX", 1, 100f);
            scaleRedBackgroundX.setDuration(200);
            scaleRedBackgroundY = ObjectAnimator.ofFloat(audioRecordBackground, "scaleY", 1, 100f);
            scaleRedBackgroundY.setDuration(200);
            saveAudio = true;
            break;

        case MotionEvent.ACTION_MOVE:
            if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_white);
                timerAudio.setVisibility(View.GONE);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_red));
                if (!animatorBackground) {
                    textRecording.setText(timeFinal);
                    if (scaleRedBackgroundX.isRunning())
                        scaleRedBackgroundX.end();
                    if (scaleRedBackgroundY.isRunning())
                        scaleRedBackgroundY.end();
                    scaleRedBackgroundY.start();
                    scaleRedBackgroundX.start();
                    animatorBackground = true;
                }
                saveAudio = false;
            } else {
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
                textRecording.setText(getString(R.string.audio_record));
                timerAudio.setVisibility(View.VISIBLE);
                if (animatorBackground) {
                    if (scaleRedBackgroundX.isRunning())
                        scaleRedBackgroundX.end();
                    if (scaleRedBackgroundY.isRunning())
                        scaleRedBackgroundY.end();
                    ViewHelper.setScaleX(audioRecordBackground, 1);
                    ViewHelper.setScaleY(audioRecordBackground, 1);
                    animatorBackground = false;
                }
                saveAudio = true;
            }
            break;
        case MotionEvent.ACTION_UP:
            textRecordingPress.setVisibility(View.VISIBLE);
            animatorBackground = false;
            if (scaleAnimY.isRunning())
                scaleAnimY.end();
            if (scaleAnimX.isRunning())
                scaleAnimX.end();
            if (scaleRedBackgroundX.isRunning())
                scaleRedBackgroundX.end();
            if (scaleRedBackgroundY.isRunning())
                scaleRedBackgroundY.end();
            ViewHelper.setScaleX(audioRecordBackground, 1);
            ViewHelper.setScaleY(audioRecordBackground, 1);
            ViewHelper.setScaleX(recordAudioButton, 1);
            ViewHelper.setScaleY(recordAudioButton, 1);
            handler.removeCallbacksAndMessages(null);
            timerAudio.setText("00:00");
            timerAudio.setVisibility(View.VISIBLE);
            textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
            textRecording.setText(getString(R.string.audio_record));
            recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
            if (finalTime > 1000) {
                mediaRecorder.stop();
                mediaRecorder.release();
            } else {
                saveAudio = false;
                mediaRecorder.release();
            }
            finalTime = 0;
            timeFinal = "";
            if (saveAudio) {
                try {
                    hideKeyBoard();
                    final MsgGroups msjAudio = new MsgGroups();
                    JSONArray targets = new JSONArray();
                    JSONArray contactos = new JSONArray(grupo.targets);
                    String contactosId = null;
                    if (SpeakSocket.mSocket != null) {
                        if (SpeakSocket.mSocket.connected()) {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (translate)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", 1);
                                        contactosId += contact.idContacto;
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                        } else {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (translate)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", -1);
                                        contactosId += contact.idContacto;
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                        }
                    }
                    msjAudio.grupoId = grupo.grupoId;
                    msjAudio.mensajeId = u.id + grupo.grupoId + fechaAudioMillis + Settings.Secure
                            .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                    msjAudio.emisor = u.id;
                    msjAudio.receptores = targets.toString();
                    msjAudio.mensaje = "new Audio";
                    msjAudio.emisorEmail = u.email;
                    msjAudio.emisorLang = u.lang;
                    msjAudio.translation = false;
                    msjAudio.emitedAt = fechaAudioMillis;
                    msjAudio.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_AUDIO));
                    msjAudio.delay = 0;
                    msjAudio.fileUploaded = false;
                    msjAudio.audioName = ficheroAudio;
                    msjAudio.save();
                    showNewMessage(msjAudio);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            } else {
                new File(ficheroAudio).delete();
            }
            break;
        }
        break;
    }

    return true;
}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

@Override
public boolean onTouch(View v, MotionEvent event) {
    int action = event.getActionMasked();
    switch (v.getId()) {
    case R.id.record_audio:
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            textRecordingPress.setVisibility(View.INVISIBLE);
            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
            fechaAudioMillis = Calendar.getInstance().getTimeInMillis();
            File directory = new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent");
            directory.mkdirs();//w  w  w .  ja  va 2 s.c om
            ficheroAudio = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Audio/Sent/"
                    + fechaAudioMillis + ".mp4";
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setOutputFile(ficheroAudio);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            try {
                mediaRecorder.prepare();
            } catch (IOException e) {
            }
            mediaRecorder.start();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    finalTime += 1000;
                    int seconds = (int) (finalTime / 1000) % 60;
                    int minutes = (int) ((finalTime / (1000 * 60)) % 60);
                    int hours = (int) ((finalTime / (1000 * 60 * 60)) % 24);
                    timeFinal = String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
                    timerAudio.setText(timeFinal);
                    if (!saveAudio) {
                        textRecording.setText(timeFinal);
                    }
                    handler.postDelayed(this, 1000);
                }
            });
            scaleAnimX = ObjectAnimator.ofFloat(recordAudioButton, "scaleX", 1, 1.2f);
            scaleAnimX.setDuration(800);
            scaleAnimX.setRepeatCount(ValueAnimator.INFINITE);
            scaleAnimX.setRepeatMode(ValueAnimator.REVERSE);
            scaleAnimY = ObjectAnimator.ofFloat(recordAudioButton, "scaleY", 1, 1.2f);
            scaleAnimY.setDuration(800);
            scaleAnimY.setRepeatCount(ValueAnimator.INFINITE);
            scaleAnimY.setRepeatMode(ValueAnimator.REVERSE);
            scaleAnimY.start();
            scaleAnimX.start();

            scaleRedBackgroundX = ObjectAnimator.ofFloat(audioRecordBackground, "scaleX", 1, 100f);
            scaleRedBackgroundX.setDuration(200);
            scaleRedBackgroundY = ObjectAnimator.ofFloat(audioRecordBackground, "scaleY", 1, 100f);
            scaleRedBackgroundY.setDuration(200);
            saveAudio = true;
            break;

        case MotionEvent.ACTION_MOVE:
            if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_white);
                timerAudio.setVisibility(View.GONE);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_red));
                if (!animatorBackground) {
                    textRecording.setText(timeFinal);
                    if (scaleRedBackgroundX.isRunning())
                        scaleRedBackgroundX.end();
                    if (scaleRedBackgroundY.isRunning())
                        scaleRedBackgroundY.end();
                    scaleRedBackgroundY.start();
                    scaleRedBackgroundX.start();
                    animatorBackground = true;
                }
                saveAudio = false;
            } else {
                recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
                textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
                textRecording.setText(getString(R.string.audio_record));
                timerAudio.setVisibility(View.VISIBLE);
                if (animatorBackground) {
                    if (scaleRedBackgroundX.isRunning())
                        scaleRedBackgroundX.end();
                    if (scaleRedBackgroundY.isRunning())
                        scaleRedBackgroundY.end();
                    ViewHelper.setScaleX(audioRecordBackground, 1);
                    ViewHelper.setScaleY(audioRecordBackground, 1);
                    animatorBackground = false;
                }
                saveAudio = true;
            }
            break;
        case MotionEvent.ACTION_UP:
            textRecordingPress.setVisibility(View.VISIBLE);
            animatorBackground = false;
            if (scaleAnimY.isRunning())
                scaleAnimY.end();
            if (scaleAnimX.isRunning())
                scaleAnimX.end();
            if (scaleRedBackgroundX.isRunning())
                scaleRedBackgroundX.end();
            if (scaleRedBackgroundY.isRunning())
                scaleRedBackgroundY.end();
            ViewHelper.setScaleX(audioRecordBackground, 1);
            ViewHelper.setScaleY(audioRecordBackground, 1);
            ViewHelper.setScaleX(recordAudioButton, 1);
            ViewHelper.setScaleY(recordAudioButton, 1);
            handler.removeCallbacksAndMessages(null);
            timerAudio.setText("00:00");
            timerAudio.setVisibility(View.VISIBLE);
            textRecording.setTextColor(getResources().getColor(R.color.speak_all_white));
            textRecording.setText(getString(R.string.audio_record));
            recordAudioButton.setBackgroundResource(R.drawable.rounded_record_audio_red);
            if (finalTime > 1000) {
                mediaRecorder.stop();
                mediaRecorder.release();
            } else {
                saveAudio = false;
                mediaRecorder.release();
            }
            finalTime = 0;
            timeFinal = "";
            if (saveAudio) {
                try {
                    hideKeyBoard();
                    final Message msjAudio = new Message();
                    String id = u.id + contact.idContacto + fechaAudioMillis + Settings.Secure
                            .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                    msjAudio.mensajeId = id;
                    msjAudio.emisor = u.id;
                    msjAudio.receptor = contact.idContacto;
                    msjAudio.emisorEmail = u.email;
                    msjAudio.receptorEmail = contact.email;
                    msjAudio.emisorLang = u.lang;
                    msjAudio.receptorLang = contact.lang;
                    msjAudio.emitedAt = fechaAudioMillis;
                    msjAudio.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_AUDIO));
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            msjAudio.status = 1;
                        } else {
                            msjAudio.status = -1;
                        }
                    msjAudio.fileUploaded = false;
                    msjAudio.audioName = ficheroAudio;
                    msjAudio.save();
                    Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjAudio.receptor)
                            .executeSingle();
                    if (chat == null) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjAudio.receptor).executeSingle();
                        Chats newChat = new Chats();
                        newChat.mensajeId = msjAudio.mensajeId;
                        newChat.idContacto = msjAudio.receptor;
                        newChat.isLockedConversation = false;
                        newChat.lastStatus = msjAudio.status;
                        newChat.email = msjAudio.receptorEmail;
                        if (contact != null) {
                            newChat.photo = contact.photo;
                            newChat.fullName = contact.fullName;
                            newChat.lang = contact.lang;
                            newChat.screenName = contact.screenName;
                            newChat.photoload = true;
                            newChat.phone = contact.phone;
                        } else {
                            newChat.photo = null;
                            newChat.photoload = false;
                            newChat.fullName = msjAudio.receptorEmail;
                            newChat.lang = msjAudio.receptorLang;
                            newChat.screenName = msjAudio.receptorEmail;
                            newChat.phone = null;
                        }
                        newChat.emitedAt = msjAudio.emitedAt;
                        newChat.notRead = 0;
                        newChat.lastMessage = "send Audio";
                        newChat.show = true;
                        newChat.save();
                    } else {
                        if (!chat.photoload) {
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", msjAudio.emisor).executeSingle();
                            if (contact != null) {
                                chat.photo = contact.photo;
                                chat.photoload = true;
                            } else {
                                chat.photo = null;
                                chat.photoload = false;
                            }
                        }
                        chat.mensajeId = msjAudio.mensajeId;
                        chat.lastStatus = msjAudio.status;
                        chat.emitedAt = msjAudio.emitedAt;
                        chat.notRead = 0;
                        chat.lastMessage = "send Audio";
                        chat.save();
                    }
                    showNewMessage(msjAudio);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            } else {
                new File(ficheroAudio).delete();
            }
            break;
        }
        break;
    }

    return true;
}