Detailed explanation of Android development recording and playing audio steps (dynamic access)

  • 2021-11-10 10:50:57
  • OfStack

Steps:

Configure permissions:


<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.work.mediaplay">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

Code steps:


public class MainActivity extends AppCompatActivity implements View.OnClickListener{
  private Button btn_start, btn_stop;
  private ListView lv_content;
  private File sdcardfile = null;
  private String[] files;
  private MediaRecorder recorder=null;


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    getSDCardFile();
    getFileList();

  }

  /**
   *  ①   Instantiate a control 
   */
  private void initView() {
    btn_start = (Button) findViewById(R.id.btn_stat);
    btn_stop = (Button) findViewById(R.id.btn_stop);
    lv_content = (ListView) findViewById(R.id.lv_content);
    // Add listening events to buttons 
    btn_start.setOnClickListener(this);
    btn_stop.setOnClickListener(this);
    // Set the start state. The start button is available and the stop button is unavailable 
    btn_start.setEnabled(true);
    btn_stop.setEnabled(false);

  }

  /**
   *  Methods of obtaining files in memory card 
   */
  private void getSDCardFile() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// Memory card exists 
          sdcardfile=Environment.getExternalStorageDirectory();// Get a directory file 
    }else {
      Toast.makeText(this," Memory card not found ",Toast.LENGTH_SHORT).show();
    }
  }
  /**
   *  ③ Get the file list ( listView Data source in) 
   *  Returns a collection of file names of the specified file type as a data source 
   */
  private void getFileList(){
    if(sdcardfile!=null){
      files=sdcardfile.list(new MyFilter());
      lv_content.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,files));
      // ⑥ Give ListView Add click-to-play events to elements in 
      lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          // Attending Define the method of playing audio 
          play(files[position]);
        }
      });
    }
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()){
      case R.id.btn_stat:
        // 8 Apply for dynamic permission to record audio 
        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED){
          ActivityCompat.requestPermissions(this,new String[]{
            android.Manifest.permission.RECORD_AUDIO},1);
        }else {
          startRecord();
        }
        break;
      case R.id.btn_stop:
        stopRcecord();
        break;
    }

  }

  /**
   *  4 Definition 1 File filters MyFilter Inner class of , Realization FilenameFilter Interface 
   *  Rewrite inside accept Method 
   */
  class MyFilter implements FilenameFilter{

    @Override
    public boolean accept(File pathname,String fileName) {
      return fileName.endsWith(".amr");
    }
  }
  /**
   *  ⑦ Define the start and pause methods for the two buttons 
   *
   */
  private void startRecord(){
    if(recorder==null){
      recorder=new MediaRecorder();
    }
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);// Set the audio source to the microphone of the mobile phone 
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);// Format Output 3gp
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);// Set the audio encoding to amr Format 
    // Get the root directory of the memory card and create a temporary file 
    try {
      File file=File.createTempFile(" Recording _",".amr",sdcardfile);
      recorder.setOutputFile(file.getAbsolutePath());// Set the file output path 
      // Prepare and start recording audio 
      recorder.prepare();
      recorder.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // Swap the available state of the two buttons after startup 
    btn_start.setEnabled(false);
    btn_stop.setEnabled(true);

  }
  private void stopRcecord(){
    if(recorder!=null){
      recorder.stop();
      recorder.release();
      recorder=null;
    }
    btn_start.setEnabled(true);
    btn_stop.setEnabled(false);
    // Refresh list data 
    getFileList();

  }
  /**
   *  Pet-name ruby rewrite onRequestPermissionsResult Method 
   *  Get the result of a dynamic permission request , Turn on recording audio again 
   */
  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if(requestCode==1&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
      startRecord();
    }else {
      Toast.makeText(this," User denied permission ",Toast.LENGTH_SHORT).show();
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  }
  /**
   *  Attending Define the method of playing audio 
   */
  private void play(String fileName){
    Intent intent=new Intent(Intent.ACTION_VIEW);
    // To play audio uri, Get from a file , Path required in file 
    Uri uri=Uri.fromFile(new File(sdcardfile.getAbsoluteFile()+File.separator+fileName));
    // Set playback data and type 
    intent.setDataAndType(uri,"audio/*");
    startActivity(intent);
  }


Related articles: