Android SDK Audio Capture

2016.04.08 21:22

졸리운_곰 조회 수:212

 

 

Audio Capture

The Android multimedia framework includes support for capturing and encoding a variety of common audio formats, so that you can easily integrate audio into your applications. You can record audio using the MediaRecorder APIs if supported by the device hardware.

This document shows you how to write an application that captures audio from a device microphone, save the audio and play it back.

Note: The Android Emulator does not have the ability to capture audio, but actual devices are likely to provide these capabilities.

Performing Audio Capture


Audio capture from the device is a bit more complicated than audio and video playback, but still fairly simple:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

  1. Create a new instance of android.media.MediaRecorder.
  2. Set the audio source using MediaRecorder.setAudioSource(). You will probably want to use MediaRecorder.AudioSource.MIC.
  3. Set output file format using MediaRecorder.setOutputFormat().
  4. Set output file name using MediaRecorder.setOutputFile().
  5. Set the audio encoder using MediaRecorder.setAudioEncoder().
  6. Call MediaRecorder.prepare() on the MediaRecorder instance.
  7. To start audio capture, call MediaRecorder.start().
  8. To stop audio capture, call MediaRecorder.stop().
  9. When you are done with the MediaRecorder instance, call MediaRecorder.release() on it. Calling MediaRecorder.release() is always recommended to free the resource immediately.

Example: Record audio and play the recorded audio

The example class below illustrates how to set up, start and stop audio capture, and to play the recorded audio file.

/*
 * The application needs to have the permission to write to external storage
 * if the output file is written to the external storage, and also the
 * permission to record audio. These permissions must be set in the
 * application's AndroidManifest.xml file, with something like:
 *
 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 * <uses-permission android:name="android.permission.RECORD_AUDIO" />
 *
 */
package com.android.audiorecordtest;

import android.app.Activity;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;

import java.io.IOException;


public class AudioRecordTest extends Activity
{
    private static final String LOG_TAG = "AudioRecordTest";
    private static String mFileName = null;

    private RecordButton mRecordButton = null;
    private MediaRecorder mRecorder = null;

    private PlayButton   mPlayButton = null;
    private MediaPlayer   mPlayer = null;

    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

    private void startPlaying() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    private void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }

    private void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mRecorder.start();
    }

    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }

    class RecordButton extends Button {
        boolean mStartRecording = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onRecord(mStartRecording);
                if (mStartRecording) {
                    setText("Stop recording");
                } else {
                    setText("Start recording");
                }
                mStartRecording = !mStartRecording;
            }
        };

        public RecordButton(Context ctx) {
            super(ctx);
            setText("Start recording");
            setOnClickListener(clicker);
        }
    }

    class PlayButton extends Button {
        boolean mStartPlaying = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onPlay(mStartPlaying);
                if (mStartPlaying) {
                    setText("Stop playing");
                } else {
                    setText("Start playing");
                }
                mStartPlaying = !mStartPlaying;
            }
        };

        public PlayButton(Context ctx) {
            super(ctx);
            setText("Start playing");
            setOnClickListener(clicker);
        }
    }

    public AudioRecordTest() {
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "/audiorecordtest.3gp";
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout ll = new LinearLayout(this);
        mRecordButton = new RecordButton(this);
        ll.addView(mRecordButton,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        mPlayButton = new PlayButton(this);
        ll.addView(mPlayButton,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
        setContentView(ll);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}

 

 

 

[출처] http://developer.android.com/intl/ko/guide/topics/media/audio-capture.html

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
53 레이아웃이란 무엇일까요? 졸리운_곰 2016.04.30 238
52 안드로이드 네트워크/쓰레드 프로그래밍 예제 - HTTP file 졸리운_곰 2016.04.30 318
51 안드로이드 와이파이 연결시 준비된 코드 실행2 졸리운_곰 2016.04.30 171
50 안드로이드 와이파이 연결시 준비된 코드 실행 졸리운_곰 2016.04.30 423
49 Worked solution for Kivy + Admob on android 졸리운_곰 2016.04.30 580
48 Broadcast Receiver로 문자(SMS) 수신해보자 file 졸리운_곰 2016.04.29 761
47 How do you get the Android's primary e-mail address (or a list of e-mail addresses)? 졸리운_곰 2016.04.29 221
46 지니모션 설치 방법 총정리 (한글키보드 + 구글플레이 설치) file 졸리운_곰 2016.04.23 1065
45 넥서스5 USB to PC 연결 뒤 아무것도 안 보인다면 file 졸리운_곰 2016.04.18 732
44 워드프레스와 모바일웹, 앱 file 졸리운_곰 2016.04.17 191
43 워드프레스 기반 안드로이드 앱 만들기 file 졸리운_곰 2016.04.17 522
42 안드로이드/Android 액티비티(Activity) 투명 처리 하기 file 졸리운_곰 2016.04.14 196
» Audio Capture 졸리운_곰 2016.04.08 212
40 [안드로이드] 앱이 파일을 읽고 쓰는 위치 졸리운_곰 2016.03.24 879
39 안드로이드 네트워크 연결 상태 확인 졸리운_곰 2016.03.23 437
38 안드로이드 > 네트워크 연결 상태를 확인하는 ConnectivityManager 졸리운_곰 2016.03.23 652
37 [펌][안드로이드예제] 카메라로 찍은 사진(이미지파일)을 웹서버에 전송하는 프로그램예제 졸리운_곰 2016.03.12 2730
36 안드로이드 통화 녹음 소스 : android call recoder source file 졸리운_곰 2016.03.12 2118
35 안드로이드 앱 : 앱 개발시 코드에서 다른 앱 설치 및 제거 졸리운_곰 2016.03.09 295
34 [Android] 첨부파일 포함한 이메일 보내기 file 졸리운_곰 2016.03.05 911
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED