+1

Tạo trình ghi âm cho Android

Creating the User Interface

Bước 1: Xây dựng giao diện người dùng cho Audio Recorder. Mình ví dụ với một màn hình đơn giản với 3 nút: một để bắt đầu ghi âm thanh, thứ hai để dừng ghi âm thanh và cuối cùng để phát ghi âm thanh.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ssaurel.audiorecorder.MainActivity">
    <ImageView
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:src="@drawable/logo_ssaurel"
        android:id="@+id/logo"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Record"
        android:textSize="20sp"
        android:id="@+id/record"
        android:layout_below="@id/logo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop"
        android:textSize="20sp"
        android:id="@+id/stop"
        android:layout_below="@id/record"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Play"
        android:textSize="20sp"
        android:id="@+id/play"
        android:layout_below="@id/stop"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

Recording and Playing Sounds

Bước tiếp theo là viết mã Java cho các động chính.

public class MainActivity extends AppCompatActivity {
    private Button play, stop, record;
    private MediaRecorder myAudioRecorder;
    private String outputFile;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play = (Button) findViewById(R.id.play);
        stop = (Button) findViewById(R.id.stop);
        record = (Button) findViewById(R.id.record);
        stop.setEnabled(false);
        play.setEnabled(false);
        // ...
   }
   
}

Chúng ta cần phải vô hiệu hóa nút dừng và phát khi hoạt động được tạo ra bằng cách gọi phương thức setEnabled với tham số false. Sau đó, chúng ta cần xác định một đường dẫn cho tệp kết quả của bản ghi. Nó sẽ được lưu trữ trong một biến String có tên outputFile:

String outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";

Ở đây, mình chọn để lưu trữ các tập tin ở gốc của thư mục lưu trữ bên ngoài. Bây giờ, bây giờ là lúc để cấu hình đối tượng MediaRecorder sẽ cho phép chúng ta ghi lại âm thanh:

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

Ta sẽ xác định nguồn âm thanh, micrô ở đây, định dạng đầu ra, bộ mã hóa âm thanh và tệp xuất mà âm thanh đã ghi sẽ được lưu.

Mã được sử dụng để bắt đầu thu âm âm thanh được định nghĩa trong cài đặt thực hiện OnClickListener cho nút ghi:

record.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                myAudioRecorder.prepare();
                myAudioRecorder.start();
            } catch (IllegalStateException ise) {
                // make something ...
            } catch (IOException ioe) {
                // make something
            }
            record.setEnabled(false);
            stop.setEnabled(true);
            Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
        }
    });

Giống như bạn có thể thấy, trước khi bắt đầu thu âm, bạn phải gọi phương thức chuẩn bị của đối tượng MediaRecorder sau đó bạn có thể gọi phương thức bắt đầu.

Thực hiện cùng một điều để thiết lập một thực hiện OnClickListener trên nút dừng:

stop.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          myAudioRecorder.stop();
          myAudioRecorder.release();
          myAudioRecorder = null;
          record.setEnabled(true);
          stop.setEnabled(false);
          play.setEnabled(true);
          Toast.makeText(getApplicationContext(), "Audio Recorder stopped", Toast.LENGTH_LONG).show();
      }
  });

Ở đây, dừng ghi âm bằng cách gọi phương thức dừng của đối tượng MediaRecorder. Sau đó, chúng ta cần gọi phương thức release. Điều cuối cùng là quản lý trạng thái nút. Vô hiệu nút dừng và cho phép các nút ghi và phát. Bây giờ, chúng ta có một tập tin âm thanh ghi lại được lưu trữ ở đường dẫn outputFile. Vì vậy, chúng ta có thể chơi các tập tin âm thanh:

play.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(outputFile);
            mediaPlayer.prepare();
            mediaPlayer.start();
            Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            // make something
        }
    }
});

Để phát tệp tin âm thanh, mình sẽ sử dụng MediaPlayer API. Mình tạo ra một ví dụ MediaPlayer và chúng tôi thiết lập đường dẫn của tệp âm thanh để phát. Trước khi chơi tập tin âm thanh, chúng ta cần phải gọi phương thức chuẩn bị của đối tượng MediaPlayer. Cuối cùng, chúng ta có thể phát tệp bằng cách gọi phương thức bắt đầu.

Complete source code for the Main Activity

Giống như bạn có thể thấy, thật đơn giản để tạo Trình ghi âm cơ bản cho Android. Ở đây, bạn có thể nhận được mã nguồn hoàn chỉnh:

public class MainActivity extends AppCompatActivity {
    private Button play, stop, record;
    private MediaRecorder myAudioRecorder;
    private String outputFile;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play = (Button) findViewById(R.id.play);
        stop = (Button) findViewById(R.id.stop);
        record = (Button) findViewById(R.id.record);
        stop.setEnabled(false);
        play.setEnabled(false);
        outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
        myAudioRecorder = new MediaRecorder();
        myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        myAudioRecorder.setOutputFile(outputFile);
        
        record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myAudioRecorder.prepare();
                    myAudioRecorder.start();
                } catch (IllegalStateException ise) {
                    // make something ...
                } catch (IOException ioe) {
                    // make something
                }
                record.setEnabled(false);
                stop.setEnabled(true);
                Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
            }
        });
        
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAudioRecorder.stop();
                myAudioRecorder.release();
                myAudioRecorder = null;
                record.setEnabled(true);
                stop.setEnabled(false);
                play.setEnabled(true);
                Toast.makeText(getApplicationContext(), "Audio Recorder successfully", Toast.LENGTH_LONG).show();
            }
        });
        
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(outputFile);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    // make something
                }
            }
        });
    }
}

Bonus

Hướng dẫn này cũng có sẵn trong video trên YouTube theo 2 phần:

Phần 1:

Phần 2:

Tham khảo : Android Pub


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí