📜  Android-音频捕获

📅  最后修改于: 2021-01-05 05:06:45             🧑  作者: Mango


Android具有内置麦克风,您可以通过麦克风捕获音频并将其存储或在手机中播放。有很多方法可以做到这一点,但是最常见的方法是通过MediaRecorder类。

Android提供MediaRecorder类来记录音频或视频。为了使用MediaRecorder类,您将首先创建MediaRecorder类的实例。其语法如下。

MediaRecorder myAudioRecorder = new MediaRecorder();

现在,您将设置source,输出和编码格式以及输出文件。它们的语法在下面给出。

myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);

在指定音频源和格式及其输出文件之后,我们可以调用这两种基本方法来准备并开始记录音频。

myAudioRecorder.prepare();
myAudioRecorder.start();

除了这些方法之外,MediaRecorder类中还列出了其他方法,这些方法使您可以更好地控制音频和视频记录。

Sr.No Method & description
1

setAudioSource()

This method specifies the source of audio to be recorded

2

setVideoSource()

This method specifies the source of video to be recorded

3

setOutputFormat()

This method specifies the audio format in which audio to be stored

4

setAudioEncoder()

This method specifies the audio encoder to be used

5

setOutputFile()

This method configures the path to the file into which the recorded audio is to be stored

6

stop()

This method stops the recording process.

7

release()

This method should be called when the recorder instance is needed.

此示例演示MediaRecorder类捕获音频,然后MediaPlayer类播放记录的音频的演示。

要尝试使用此示例,您需要在实际设备上运行它。

Steps Description
1 You will use Android studio IDE to create an Android application and name it as AudioCapture under a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add AudioCapture code
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4 Modify AndroidManifest.xml to add necessary permissions.
5 Run the application and choose a running android device and install the application on it and verify the results.

这是src / MainActivity.java的内容

package com.example.sairamkrishna.myapplication;

import android.media.MediaPlayer;
import android.media.MediaRecorder;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;

import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

   Button buttonStart, buttonStop, buttonPlayLastRecordAudio, 
      buttonStopPlayingRecording ;
   String AudioSavePathInDevice = null;
   MediaRecorder mediaRecorder ;
   Random random ;
   String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
   public static final int RequestPermissionCode = 1;
   MediaPlayer mediaPlayer ;

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

      buttonStart = (Button) findViewById(R.id.button);
      buttonStop = (Button) findViewById(R.id.button2);
      buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
      buttonStopPlayingRecording = (Button)findViewById(R.id.button4);

      buttonStop.setEnabled(false);
      buttonPlayLastRecordAudio.setEnabled(false);
      buttonStopPlayingRecording.setEnabled(false);

      random = new Random();

      buttonStart.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {

            if(checkPermission()) {

               AudioSavePathInDevice = 
                  Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + 
                     CreateRandomAudioFileName(5) + "AudioRecording.3gp";

               MediaRecorderReady();

               try {
                  mediaRecorder.prepare();
                  mediaRecorder.start();
               } catch (IllegalStateException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               }

               buttonStart.setEnabled(false);
               buttonStop.setEnabled(true);

               Toast.makeText(MainActivity.this, "Recording started", 
                  Toast.LENGTH_LONG).show();
            } else {
               requestPermission();
            }

         }
      });

      buttonStop.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            mediaRecorder.stop();
            buttonStop.setEnabled(false);
            buttonPlayLastRecordAudio.setEnabled(true);
            buttonStart.setEnabled(true);
            buttonStopPlayingRecording.setEnabled(false);

            Toast.makeText(MainActivity.this, "Recording Completed", 
               Toast.LENGTH_LONG).show();
         }
      });

      buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) throws IllegalArgumentException, 
            SecurityException, IllegalStateException {
               
            buttonStop.setEnabled(false);
            buttonStart.setEnabled(false);
            buttonStopPlayingRecording.setEnabled(true);

            mediaPlayer = new MediaPlayer();
            try {
               mediaPlayer.setDataSource(AudioSavePathInDevice);
               mediaPlayer.prepare();
            } catch (IOException e) {
               e.printStackTrace();
            }

            mediaPlayer.start();
            Toast.makeText(MainActivity.this, "Recording Playing", 
               Toast.LENGTH_LONG).show();
         }
      });

      buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            buttonStop.setEnabled(false);
            buttonStart.setEnabled(true);
            buttonStopPlayingRecording.setEnabled(false);
            buttonPlayLastRecordAudio.setEnabled(true);

            if(mediaPlayer != null){
               mediaPlayer.stop();
               mediaPlayer.release();
               MediaRecorderReady();
            }
         }
      });
      
   }

   public void MediaRecorderReady(){
      mediaRecorder=new MediaRecorder();
      mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
      mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
      mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
      mediaRecorder.setOutputFile(AudioSavePathInDevice);
   }

   public String CreateRandomAudioFileName(int string){
      StringBuilder stringBuilder = new StringBuilder( string );
      int i = 0 ;
      while(i < string ) {   
         stringBuilder.append(RandomAudioFileName.
            charAt(random.nextInt(RandomAudioFileName.length())));

         i++ ;
      }
      return stringBuilder.toString();
   }

   private void requestPermission() {
      ActivityCompat.requestPermissions(MainActivity.this, new 
         String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
   }

   @Override
   public void onRequestPermissionsResult(int requestCode, 
      String permissions[], int[] grantResults) {
      switch (requestCode) {
         case RequestPermissionCode:
            if (grantResults.length> 0) {
            boolean StoragePermission = grantResults[0] == 
               PackageManager.PERMISSION_GRANTED;
            boolean RecordPermission = grantResults[1] == 
               PackageManager.PERMISSION_GRANTED;
                     
            if (StoragePermission && RecordPermission) {
               Toast.makeText(MainActivity.this, "Permission Granted", 
                  Toast.LENGTH_LONG).show();
            } else {
               Toast.makeText(MainActivity.this,"Permission 
                  Denied",Toast.LENGTH_LONG).show();
            }
         }
         break;
      }
   }

   public boolean checkPermission() {
      int result = ContextCompat.checkSelfPermission(getApplicationContext(), 
         WRITE_EXTERNAL_STORAGE);
      int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), 
         RECORD_AUDIO);
      return result == PackageManager.PERMISSION_GRANTED && 
         result1 == PackageManager.PERMISSION_GRANTED;
   }
}

这是activity_main.xml的内容

在下面的代码中abc表示tutorialspoint的徽标




   

   

   

   

   

这是Strings.xml的内容


   My Application

这是AndroidManifest.xml的内容



   
   
    
     

   
      
      
      
         
            
            
         
      
      
      
   

让我们尝试运行您的应用程序。我假设您已将实际的Android Mobile设备与计算机连接。要从Android Studio运行该应用,请打开您项目的活动文件之一,然后点击运行Eclipse运行图标工具栏中的图标。在启动您的应用程序之前,Android Studio将显示以下图像。

现在默认情况下,您将看到停止和播放按钮禁用。只需按“录制”按钮,您的应用程序便会开始录制音频。它将显示以下屏幕。

声音录制

现在只需按停止按钮,它将把录制的音频保存到外部SD卡。当您单击停止按钮时,将出现以下屏幕。

Android停止按钮

现在,只要按一下播放按钮,录制的音频就会开始在设备上播放。当您单击播放按钮时,将显示以下消息。

Android播放按钮