Team-Mobile Notes-development documentation

Source: Internet
Author: User
Tags gettext save file hosting

Project Hosting platform Address : Https://github.com/Vcandoit/Notepad.git

Because we are team development, we write the code directly to the team, we have someone responsible for the merger of the code, so we directly merge the code to deal with the

So I didn't write my own hosting platform, and our team was posted on a single person's hosting platform.

I was responsible for the development of the recording function block,

First of all, I designed the recording UI to complete the writing of what is needed

Let me tell you how to use:

First we click and hold the speech, note that the time to talk more than three seconds, because I in the program to judge, less than three seconds of voice we do not save, will prompt you to record the failure,

Then when you press and hold the talk button, you will notice that the word becomes the word being recorded, then you can record it, and when you have finished recording it will prompt you to record it successfully, how many seconds.

Finally click the Play button and you'll be able to hear your recording.

To develop a functional implementation process:

First I want to get access to the permissions, add microphone permissions, more than 6.0 of the version to use the program to get the microphone usage rights

Then I write the recorder, first I want to get the audio, and then save the accepted audio file to the local private directory, and then click the Play button to get audio files from the private directory to play.

Package Com.example.apple.tuandui;

Import Android. Manifest;
Import android.content.Intent;
Import Android.content.pm.PackageManager;
Import Android.media.MediaPlayer;
Import Android.media.MediaRecorder;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Looper;
Import Android.support.v4.app.ActivityCompat;
Import Android.support.v4.content.ContextCompat;
Import android.support.v7.app.AppCompatActivity;
Import android.view.MotionEvent;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.ImageButton;
Import Android.widget.TextView;
Import Android.widget.Toast;
Import Java.io.File;
Import java.io.IOException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Butterknife. BindView;
Import Butterknife. Butterknife;
Import Butterknife. OnClick;

/**
* Created by Apple on 2017/10/25.
*/

public class Radioactivity extends Appcompatactivity {

@BindView (R.ID.ANJIAN_BTN)
Button anjian_btn;

@BindView (R.id.text)
TextView text;

Multithreaded background processing
Private Executorservice Mexecutorservice;

Private Mediarecorder Mmediarecorder;

Private File Maudiofile;

Private long mstartrecordtime, mstoprecordtime;

Private Handler mmainthreadhandler;//Main thread
Main thread and background playback threading data synchronization
Private volatile Boolean misplaying;

Private MediaPlayer Mmediaplayer;

Private ImageButton back_btn;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_radio);

BACK_BTN = (ImageButton) Findviewbyid (R.id.fanhui);

if (Contextcompat.checkselfpermission (this,
Manifest.permission.RECORD_AUDIO)
! = packagemanager.permission_granted)
{
//
Activitycompat.requestpermissions (This,
New String[]{manifest.permission.record_audio},
1);
}

Butterknife.bind (this);
The recording JNI function does not have thread safety, so calling a single thread
Mexecutorservice = Executors.newsinglethreadexecutor ();
Mmainthreadhandler = new Handler (Looper.getmainlooper ());

Press speak to release the send so we don't onclicklistener
Anjian_btn.setontouchlistener (New View.ontouchlistener () {
@Override
public Boolean OnTouch (view view, Motionevent motionevent) {
Perform different logic based on different touch action
Switch (motionevent.getaction ()) {
Case Motionevent.action_down:
Startrecord ();
Break
Case MOTIONEVENT.ACTION_UP:
Case Motionevent.action_cancel:
Stoprecord ();
Break
Default
Break
}
Handled the touch event, returning True
return true;
}
});
}
Simplifying code with Butterknife
@OnClick (R.ID.PLAY_BTN)
public void Play () {
Check the current state to prevent repeated playback
if (maudiofile!=null&&!misplaying) {
Set Current playback status
Misplaying = true;
Submit a background task to start playing
Mexecutorservice.submit (New Runnable () {
@Override
public void Run () {
Doplay (Maudiofile);

}
});
}


}


@Override
protected void OnDestroy () {
Super.ondestroy ();

When activity is destroyed, stop background tasks and avoid memory leaks
Mexecutorservice.shutdownnow ();
Releaserecorder ();
Stopplay ();
}


/***
*
* Start Recording
*/
private void Startrecord () {
Changing UI State
Anjian_btn.settext ("talking");
Anjian_btn.setbackgroundresource ();

Submit background task, execute recording logic
Mexecutorservice.submit (New Runnable () {
@Override
public void Run () {
Mediarecorder before releasing the recording
Releaserecorder ();
Executes the recording logic if the user is prompted to fail
if (!dostart ()) {
Recordfail ();
}
}
});
}


/***
*
* Stop Recording
*/

private void Stoprecord () {
Changing UI State
Anjian_btn.settext ("Hold to speak");
Anjian_btn.setbackgroundresource ();
Submit a background task, execution stop logic
Mexecutorservice.submit (New Runnable () {
@Override
public void Run () {
Execute stop recording logic, fail to remind user
if (!dostop ()) {
Recordfail ();
}
Release Mediarecorder
Releaserecorder ();
}
});
}


/**
* Start Recording logic
*/
Private Boolean Dostart () {

try {
Create Mediarecorder
Mmediarecorder = new Mediarecorder ();
Create a recording file
Get absolute path

Maudiofile = new File (Getexternalfilesdir (null). GetAbsolutePath () +
"/liuming/" + system.currenttimemillis () + ". m4a");


Maudiofile = new File (Environment.getexternalstoragedirectory (). GetAbsolutePath () +alstoragedirectory (). GetA Bsolutepath () +
"/liuming/" + system.currenttimemillis () + ". m4a");
Maudiofile.getparentfile (). Mkdirs ();
Maudiofile.createnewfile ();

Configure Mediarecorder

(1)//from the Microphone collection
Mmediarecorder.setaudiosource (MediaRecorder.AudioSource.MIC);

(2) Save file as MP4 format
Mmediarecorder.setoutputformat (MediaRecorder.OutputFormat.MPEG_4);

(3) Sampling frequency supported by all Android systems
Mmediarecorder.setaudiosamplingrate (44100);

General-Purpose AAC encoding format
Mmediarecorder.setaudioencoder (MediaRecorder.AudioEncoder.AAC);

A frequency with better sound quality
Mmediarecorder.setaudioencodingbitrate (96000);

Set as File save location
Mmediarecorder.setoutputfile (Maudiofile.getabsolutepath ());

Start recording
Mmediarecorder.prepare ();//Preparation
Mmediarecorder.start ();//Start

Record the time the recording started, used for statistical time
Mstartrecordtime = System.currenttimemillis ();


} catch (IOException | RuntimeException e) {
E.printstacktrace ();
Catch exception, avoid flashback, return false reminder user failed
return false;
}
Recording success
return true;
}

/**
* Stop Recording logic
*/

Private Boolean dostop () {


try {
Stop Recording
Mmediarecorder.stop ();
Record stop time, statistics time
Mstoprecordtime = System.currenttimemillis ();

Only take more than three seconds of recording and display it on the UI
Final int second = (int) ((mstoprecordtime-mstartrecordtime)/1000);
if (Second > 3) {
Text.settext (Text.gettext () + "\ n Recording Success" + Second + "seconds");
Change UI in the main thread, display it
Mmainthreadhandler. Post (new Runnable () {
@Override
public void Run () {
Text.settext (Text.gettext () + "\ n Recording succeeded" +second+ "seconds");
}
});
}
} catch (RuntimeException e) {
E.printstacktrace ();
Catch exception, avoid flashback, return false reminder user failed
return false;
}


Stop successful
return true;
}

/**
* Release Mediarecorder
*/

private void Releaserecorder () {
Check that Mediarecorder is not NULL,
if (Mmediarecorder! = null) {
Mmediarecorder.release ();
Mmediarecorder = null;
}
}

/**
* Recording error handling
*/

private void Recordfail () {
Maudiofile = null;
The toast prompt to the user failed to execute on the main thread
Mmainthreadhandler.post (New Runnable () {
@Override
public void Run () {
Toast.maketext (Radioactivity.this, "Recording failed", Toast.length_short). Show ();

}
});

}

/**
* Implement playback logic
* @param audioFile
*/

private void Doplay (File audioFile) {

Configuring the Player MediaPlayer
Mmediaplayer = new MediaPlayer ();
try {
Setting up sound files
Mmediaplayer.setdatasource (Audiofile.getabsolutepath ());

Sets the listener callback.
Mmediaplayer.setoncompletionlistener (New Mediaplayer.oncompletionlistener () {
@Override
public void Oncompletion (MediaPlayer MP) {
Play end, release player
Stopplay ();
}
});
Mmediaplayer.setonerrorlistener (New Mediaplayer.onerrorlistener () {
@Override
public Boolean onError (MediaPlayer MP, int. what, int extra) {
Prompt user
Playfail ();

Release player
Stopplay ();

Error has been processed, return true
return true;
}
});
Set volume, whether looping
Mmediaplayer.setvolume (//,1,1), left and right channel
Mmediaplayer.setlooping (false);//Do not need to play repeatedly
Get ready, Get started
Mmediaplayer.prepare ();
Mmediaplayer.start ();
}catch (RuntimeException | IOException e) {
Exception handling to prevent flash-back
E.printstacktrace ();
Remind users
Playfail ();
Release player
Stopplay ();
}
}


/**
*
* Stop playback logic
*/
private void Stopplay () {

Reset Playback Status
Misplaying = false;
Release player
if (mmediaplayer!=null) {
Set up listeners to prevent memory leaks
Mmediaplayer.setoncompletionlistener (NULL);
Mmediaplayer.setonerrorlistener (NULL);
Mmediaplayer.stop ();
Mmediaplayer.reset ();
Mmediaplayer.release ();
Mmediaplayer = null;

}
}

/**
*
* Remind users to play failed
*/
private void Playfail () {
A toast prompt user fails on the main thread
Mmainthreadhandler.post (New Runnable () {
@Override
public void Run () {
Toast.maketext (Radioactivity.this, "playback failed", Toast.length_long). Show ();
}
});
}
public void back (view view) {
StartActivity (New Intent (This,mainactivity.class));
}



}

Team-Mobile Notes-development documentation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.