在Android中以特定时间间隔进行录音 [英] Audio recording in android with particular time interval

查看:143
本文介绍了在Android中以特定时间间隔进行录音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的活动中有两种方法,一种是setOnClickListener(),另一种是setOnLongClickListener()
与用于开始录音的按钮相同.

I have two method in my activity one is setOnClickListener() and other is setOnLongClickListener()
For the same button which used to start audio recording.

现在我不知道如何使用条件,如果我使用setOnClickListener(),则录制应开始1分钟并自动停止;如果我使用setOnLongClickListener(),则录制应开始2分钟,然后自动停止./p>

Now i don't know how to use condition, if i use setOnClickListener() then recording should start for 1 minute and stop automatically, and if i use setOnLongClickListener() then recording start for 2 minute and then stop automatically.

buttonStart.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(Record_Audio.this,
                    "Start Recording With LongClick", Toast.LENGTH_SHORT)
                    .show();
            enableButtons(true);
            startRecording();
            return true;
        }
    });


private View.OnClickListener btnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnStart: {
            Toast.makeText(Record_Audio.this, "Start Recording",
                    Toast.LENGTH_SHORT).show();
            enableButtons(true);
            startRecording();
            break;
        }
}
});

private void startRecording() {
    displayAlertDialog();
}


private void displayAlertDialog() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Record_Audio.this);

    alertDialog.setTitle("Would you Like to save your Recording");
    alertDialog.setMessage("Enter Audio Name");
    alertDialog.setIcon(R.drawable.save_icon);

    final EditText editTextAudioName = new EditText(Record_Audio.this);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);

    editTextAudioName.setLayoutParams(lp);
    alertDialog.setView(editTextAudioName);

    alertDialog.setPositiveButton("Save",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    Code.audioName = editTextAudioName.getText().toString()
                            .trim();

                    recorder = new MediaRecorder();
                    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    recorder.setOutputFormat(output_formats[currentFormat]);
                    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    recorder.setOutputFile(getFilename());
                    recorder.setOnErrorListener(errorListener);
                    recorder.setOnInfoListener(infoListener);
                    try {
                        recorder.prepare();
                        recorder.start();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    myChronometer.setBase(SystemClock.elapsedRealtime());
                    myChronometer.start();
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to execute after dialog
                    dialog.cancel();
                }
            });
    alertDialog.show();
}

我知道我必须在特定的时间间隔内使用setMaxDuration,但是我不知道如何使用这两种方法.

I know i have to use setMaxDuration for particular time interval, but i don't know how to use with this two method.

谢谢.

推荐答案

无论如何,MediaRecorder Api都不是使用录制音频的好方法.请使用AudioRecorder API.

Anyhow the MediaRecorder Api is not good way to use record audio.Use the AudioRecorder API.

让我解释一下

1.这是录制音频的类

1.This is class for recording audio

公开课Taukyrecorder {

public class Taukyrecorder {

private static final int RECORDER_BPP = 16;
private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".mp3";
private static final String AUDIO_RECORDER_FOLDER = "/'/'";
private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw";
private static final int RECORDER_SAMPLERATE = 44100;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

private AudioRecord recorder = null;
private int bufferSize = 0;
private Thread recordingThread = null;
public static boolean isRecording = false;
int numCrossing, p;

public int frequency;

int blockSize = 3500;
private Context mcontext;



public static String final_sound_path = null;

Handler handler;

RecorderListener mylistener;

public Taukyrecorder(Context cntxt) {
    // TODO Auto-generated constructor stub
    mcontext = cntxt;

    // Log.i("Recorder", "helllllo");

    InitRecord();

}

public void RegisterListener(RecorderListener listener) {

    this.mylistener = listener;
}

public void InitRecord()
{
    handler = new Handler();

    bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
            RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);

    recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
            RECORDER_SAMPLERATE, RECORDER_CHANNELS,
            RECORDER_AUDIO_ENCODING, bufferSize);

    recorder.setRecordPositionUpdateListener(
            new OnRecordPositionUpdateListener() {

                @Override
                public void onPeriodicNotification(AudioRecord recorder) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onMarkerReached(AudioRecord recorder) {
                    // TODO Auto-generated method stub

                }
            }, handler);

}

// Get the file for saving sound into the folder
public File GetFileTOwriteSound() {
    File tempPicFile = null;
    String ext_storage_state = Environment.getExternalStorageState();
    File mediaStorage = new File(Environment.getExternalStorageDirectory()
            + "/TAUKY/SOUNDS");
    if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
        if (!mediaStorage.exists()) {
            mediaStorage.mkdirs();
        } else {
            // do nothing
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        tempPicFile = new File(mediaStorage.getPath() + File.separator
                + "SOUND_" + timeStamp + ".mp3");

    } else {

        Toast.makeText(mcontext, "NO SDCARD MOUNTED", 1).show();

    }
    return tempPicFile;
}

private String getTempFilename() {
    String filepath = Environment.getExternalStorageDirectory().getPath();
    File file = new File(filepath, AUDIO_RECORDER_FOLDER);

    if (!file.exists()) {
        file.mkdirs();
    }

    File tempFile = new File(filepath, AUDIO_RECORDER_TEMP_FILE);

    if (tempFile.exists())
        tempFile.delete();

    return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_TEMP_FILE);
}

public void startRecording() {


    //InitRecord();

    recorder.startRecording();

    isRecording = true;

    recordingThread = new Thread(new Runnable() {

        @Override
        public void run() {
            writedataToFile();
        }
    }, "AudioRecorder Thread");

    recordingThread.start();
}

private void writedataToFile() {
    byte data[] = new byte[bufferSize];
    String filename = getTempFilename();
    FileOutputStream os = null;

    try {
        os = new FileOutputStream(filename);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    int read = 0;

    short[] buffer = new short[blockSize];
    double[] toTransform = new double[blockSize];


    if (null != os) {
        while (isRecording) {

            read = recorder.read(data, 0, bufferSize);

            if (AudioRecord.ERROR_INVALID_OPERATION != read) {
                try {
                    os.write(data);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //int bufferReadResult = recorder.read(buffer, 0, blockSize);



                //byte[] bData= {};
                short[] sData= new short[data.length/2];
                // to turn bytes to shorts as either big endian or little endian. 
                ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(sData);




                for (int i = 0; i < blockSize && i < read; i++) {
                    toTransform[i] = sData[i] / 32768.0; 
                }



                mylistener.Updatevalues(toTransform);

            }
        }

        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public void stopRecording() {
    String getfilename = GetFileTOwriteSound().getAbsolutePath();
    final_sound_path = getfilename;
    if (null != recorder) {
        isRecording = false;

        recorder.stop();
        recorder.release();

        recorder = null;
        recordingThread = null;
    }

    copyWaveFile(getTempFilename(), getfilename);
    deleteTempFile();
}

private void deleteTempFile() {
    File file = new File(getTempFilename());

    file.delete();
}

private void copyWaveFile(String inFilename, String outFilename) {
    FileInputStream in = null;
    FileOutputStream out = null;
    long totalAudioLen = 0;
    long totalDataLen = totalAudioLen + 36;
    long longSampleRate = RECORDER_SAMPLERATE;
    int channels = 2;
    long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8;

    byte[] data = new byte[bufferSize];

    try {
        in = new FileInputStream(inFilename);
        out = new FileOutputStream(outFilename);
        totalAudioLen = in.getChannel().size();
        totalDataLen = totalAudioLen + 36;

        // /AppLog.logString("File size: " + totalDataLen);

        WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
                longSampleRate, channels, byteRate);

        while (in.read(data) != -1) {
            out.write(data);
        }

        in.close();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void WriteWaveFileHeader(FileOutputStream out, long totalAudioLen,
        long totalDataLen, long longSampleRate, int channels, long byteRate)
        throws IOException {

    byte[] header = new byte[44];

    header[0] = 'R'; // RIFF/WAVE header
    header[1] = 'I';
    header[2] = 'F';
    header[3] = 'F';
    header[4] = (byte) (totalDataLen & 0xff);
    header[5] = (byte) ((totalDataLen >> 8) & 0xff);
    header[6] = (byte) ((totalDataLen >> 16) & 0xff);
    header[7] = (byte) ((totalDataLen >> 24) & 0xff);
    header[8] = 'W';
    header[9] = 'A';
    header[10] = 'V';
    header[11] = 'E';
    header[12] = 'f'; // 'fmt ' chunk
    header[13] = 'm';
    header[14] = 't';
    header[15] = ' ';
    header[16] = 16; // 4 bytes: size of 'fmt ' chunk
    header[17] = 0;
    header[18] = 0;
    header[19] = 0;
    header[20] = 1; // format = 1
    header[21] = 0;
    header[22] = (byte) channels;
    header[23] = 0;
    header[24] = (byte) (longSampleRate & 0xff);
    header[25] = (byte) ((longSampleRate >> 8) & 0xff);
    header[26] = (byte) ((longSampleRate >> 16) & 0xff);
    header[27] = (byte) ((longSampleRate >> 24) & 0xff);
    header[28] = (byte) (byteRate & 0xff);
    header[29] = (byte) ((byteRate >> 8) & 0xff);
    header[30] = (byte) ((byteRate >> 16) & 0xff);
    header[31] = (byte) ((byteRate >> 24) & 0xff);
    header[32] = (byte) (2 * 16 / 8); // block align
    header[33] = 0;
    header[34] = RECORDER_BPP; // bits per sample
    header[35] = 0;
    header[36] = 'd';
    header[37] = 'a';
    header[38] = 't';
    header[39] = 'a';
    header[40] = (byte) (totalAudioLen & 0xff);
    header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
    header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
    header[43] = (byte) ((totalAudioLen >> 24) & 0xff);

    out.write(header, 0, 44);
}

}

开始和停止记录

MainActivity

TaukkyRecordr taukyrecorder=new Taukyrecorder(mcontext);

taukyrecorder.startRecording();

//For stop
taukyrecorder.stopRecording();

如果要在几秒钟后自动停止,请创建一个线程.

If you want stop automatically after few second please create one thread.

public class StopRecord extends Thread {
    int i = 0;

    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();

        handler.post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                taukyrecorder.stopRecording();

            }
        });


    }
}

然后使用处理程序调用线程

Then call the thread using handler

Handker mhandler=new Handeler;

mhandler.postDelayed(mRunnable, 1000);//put your secodn here

这篇关于在Android中以特定时间间隔进行录音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆