【Processing】Android プログラミング Xperia Touchのマイクから値を取得する
Xperia touch のマイクから外部の音を取得
Xperia touch 外観 マイクは上部、ボタンのならびにある。
かなりエラーに引っかかったので、今回は忘備録のような感じです。
Processing 側コードを書く
// WARNING! Be sure that your Sketch have active this permissions: // RECORD_AUDIO // WRITE_EXTERNAL_STORAGE import android.app.Activity; import android.os.Bundle; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; short[] buffer = null; AudioRecord audioRecord = null; int SAMPLING_RATE = 11025; float volume = 0; int bufSize; void setup() { // calculate buffer size bufSize = AudioRecord.getMinBufferSize( SAMPLING_RATE, AudioFormat.CHANNEL_IN_STEREO, //CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) * 2; // AudioRecord settings audioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, SAMPLING_RATE, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, bufSize); audioRecord.startRecording(); buffer = new short[bufSize]; } void draw() { background(200); int bufferReadResult = audioRecord.read(buffer, 0, bufSize); // for trouble shooting when android device doesn't work. Check error code following link // https://developer.android.com/reference/android/media/AudioFormat // println( bufferReadResult); volume = 100; for (int i = 0; i < bufferReadResult; i++) { volume = Math.max(Math.abs(buffer[i]), volume); } text("" + volume, 100, 100); //draw a box if you blow the mic if(volume>300)rect(10,10,20,20); //println(volume); // for output on the console } void stop() { audioRecord.stop(); audioRecord.release(); audioRecord = null; }
AndroidManifest.xmlのセッティングをする
<?xml version="1.0" encoding="UTF-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package=""> <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="26"/> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.RECORD_AUDIO"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:icon="@drawable/icon" android:label=""> <activity android:name=".MainActivity" android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
Xperia touch 側のセッティングをする
マニフェストに書いた許可が新しいAndroidのバージョンだとうまく権限が変更されないそうなので、こちら側も変更しておきます。
アプリケーションの権限を許可する。
一回、processingで書き込みをすると設定のAppsの中に保存したPeocessingのコード名のアプリケーションとして、
入っているので、そこをタップ
Apps ← [アプリケーションの名前] ← permissions <- Microphone とStrage を許可に変更
マイクのセッティング
設定 ← Accessory settings ← Mic sensitivity <- Highに変更
これで、もう一度processing側を書き込むと私の場合はうまくいきました。
使用環境
- Processing 3.3.5
- Android OS ver 7.1.1