2018/10/30

[Android] Get Amplitude from Device Microphone

本篇寫從手機裝置的麥克風,取得音量的大小。
建立一個 class SoundMeter.java :
class SoundMeter {

    private MediaRecorder mRecorder = null;

    void start() throws IOException {
        if (mRecorder == null) {
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setOutputFile("/dev/null");
            mRecorder.prepare();
            mRecorder.start();
        }
    }

    void stop() {
        if (mRecorder != null) {
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
    }

    double getAmplitude() {
        if (mRecorder != null)
            return  mRecorder.getMaxAmplitude();
        else
            return 0;
    }
}

MainActivity.java:
public class MainActivity extends AppCompatActivity{

    private static Handler exHandler;
    private static SoundMeter mSoundMeter;

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

        // set the getting amplitude handler
        exHandler = new Handler();

        // set up SoundMeter
        mSoundMeter = new SoundMeter();
        try {
            mSoundMeter.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume(){
        super.onResume();
        exHandler.postDelayed(pollTask, 100);
    }

    @Override
    protected void onPause(){
        super.onPause();
        exHandler.removeCallbacks(pollTask);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        mSoundMeter.stop();
        exHandler.removeCallbacks(pollTask);
    }

    private static Runnable pollTask = new Runnable() {
        @Override
        public void run() {

            // get amplitude from microphone
            double volume = mSoundMeter.getAmplitude();
            Log.d("MainActivity", "Volume: " + volume);

            // get handler per 0.1 second
            exHandler.postDelayed(pollTask, 100);
        }
    };
}

在AndroidManifest.xml加入權限:
<uses-permission android:name="android.permission.RECORD_AUDIO" />

END

沒有留言:

張貼留言