AndroidAudioRecordNode.java
Go to the documentation of this file.
00001 package org.ros.android.android_camera_viewer;
00002 
00003 import java.io.ByteArrayOutputStream;
00004 import java.io.File;
00005 import java.io.FileInputStream;
00006 import java.io.FileOutputStream;
00007 import java.io.IOException;
00008 import java.util.ArrayList;
00009 import java.util.List;
00010 
00011 import android.util.AttributeSet;
00012 import org.ros.android.MessageCallable;
00013 import org.ros.message.MessageListener;
00014 import org.ros.namespace.GraphName;
00015 import org.ros.node.ConnectedNode;
00016 import org.ros.node.NodeMain;
00017 import org.ros.node.topic.Publisher;
00018 import org.ros.node.topic.Subscriber;
00019 
00020 import android.content.Intent;
00021 import android.hardware.SensorEventListener;
00022 import android.hardware.SensorManager;
00023 import android.hardware.Sensor;
00024 import android.hardware.SensorEvent;
00025 
00026 
00027 import android.os.Bundle;
00028 import android.os.Environment;
00029 import android.os.Looper;
00030 import android.speech.RecognitionListener;
00031 import android.speech.RecognizerIntent;
00032 import android.speech.SpeechRecognizer;
00033 import android.util.Log;
00034 import android.widget.Button;
00035 import jsk_gui_msgs.VoiceMessage;
00036 import android.view.View;
00037 
00038 //add
00039 import android.media.AudioManager;
00040 import android.media.AudioRecord;
00041 import android.media.AudioTrack;
00042 import android.media.MediaRecorder;
00043 import android.media.AudioFormat;
00044 import android.util.Log;
00045 import audio_common_msgs.AudioData;
00046 import org.ros.node.ConnectedNode;
00047 import org.ros.node.topic.Publisher;
00048 import static org.jboss.netty.buffer.ChannelBuffers.*;
00049 import org.jboss.netty.buffer.ChannelBuffer;
00050 import java.nio.ByteBuffer;
00051 
00052 import org.ros.node.*;
00053 
00054 
00055 public class AndroidAudioRecordNode implements NodeMain {
00056 
00057 
00058 
00059     private int[] flag;
00060     private int startFlag = 0;
00061     private int audioFlag = 0;
00062     private String package_name;
00063 
00064     //add
00065     private Publisher<audio_common_msgs.AudioData> audio_pub;
00066     private Subscriber<audio_common_msgs.AudioData> audio_sub;
00067     private audio_common_msgs.AudioData audio_msg;
00068     final static int SAMPLING_RATE = 11025; //8000,11025,16000,22050,44100
00069     AudioRecord audioRec = null;
00070     AudioTrack audioTra = null;
00071     int bufSize;
00072 
00073     
00074     
00075      
00076     @Override
00077         public GraphName getDefaultNodeName() {
00078         return GraphName.of("audio_common_msgs/AudioRecord");
00079     }
00080 
00081     public AndroidAudioRecordNode(String package_name){
00082         this.package_name = package_name;
00083     }
00084 
00085 
00086 
00087     @Override
00088         public void onStart(final ConnectedNode connectedNode) {
00089                                 Log.v("service","fire!==================================--");
00090                                 
00091                         audio_sub = connectedNode.newSubscriber("audio2", "audio_common_msgs/AudioData");
00092                          audio_sub.addMessageListener(new MessageListener<audio_common_msgs.AudioData>() {
00093                               @Override
00094                               public void onNewMessage(final audio_common_msgs.AudioData message) {
00095                                   //Log.v("test",message.getData());
00096                                   //Log.v("test",message.toString());
00097                                 ChannelBuffer heapBuffer = message.getData();
00098                                 byte buf[] = new byte[heapBuffer.readableBytes()];
00099                                 heapBuffer.readBytes(buf,0,heapBuffer.readableBytes());
00100                                   Log.v("test",buf[0]+","+buf[1]);
00101                                   if(audioFlag > 0){ // 動かすときは>0
00102                                   //audioTra.reloadStaticData();
00103                                   Log.v("state",""+audioTra.getState());
00104                                   audioTra.write(buf, 0, buf.length);
00105                                   audioTra.play();
00106                                   
00107                                   }
00108                               }
00109                             });
00110                                 
00111                       //バッファサイズの計算
00112     bufSize = AudioRecord.getMinBufferSize(
00113                                            SAMPLING_RATE,
00114                                            AudioFormat.CHANNEL_CONFIGURATION_MONO,
00115                                            AudioFormat.ENCODING_PCM_16BIT)*2;
00116     try{
00117 
00118         audio_pub = connectedNode.newPublisher("audio","audio_common_msgs/AudioData");
00119         Log.v("test","publish start===================================="+bufSize);
00120         startFlag=1;
00121 
00122     }catch (Exception e){
00123                           
00124     }
00125 
00126     //AudioRecordの作成
00127     audioRec = new AudioRecord(
00128                                MediaRecorder.AudioSource.MIC,
00129                                SAMPLING_RATE,
00130                                AudioFormat.CHANNEL_CONFIGURATION_MONO,
00131                                AudioFormat.ENCODING_PCM_16BIT,
00132                                bufSize);
00133         
00134     //AudioPlayの作成
00135 
00136         audioTra = new AudioTrack(
00137                         AudioManager.STREAM_MUSIC,                //streamType STREAM_MUSIC
00138             SAMPLING_RATE,                        //sampleRateInHz:サンプリング周波数
00139             AudioFormat.CHANNEL_CONFIGURATION_MONO,    //channelConfig(モノラル指定)
00140             AudioFormat.ENCODING_PCM_16BIT,            //audioFormat
00141             bufSize*10,                        //bufferSizeInBytes:バッファサイズ(奇数だとエラーになる模様
00142             AudioTrack.MODE_STREAM);                //mode(STATICモード指定)
00143                         
00144     audioFlag = 1;
00145         Log.v("AudioRecord","startRecording");
00146         audioRec.startRecording();
00147         
00148         //Record
00149         new Thread(new Runnable(){
00150                 @Override
00151                     public void run(){
00152 
00153                         
00154                     //new!
00155                         try{
00156                  // 録音用ファイル取得  SDカード状態チェック略
00157                     File recFile =new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/rec.raw");
00158                     recFile.createNewFile();
00159                     // ファイル書き込み  例外処理略
00160                     FileOutputStream out =  new FileOutputStream(recFile);
00161                         
00162                     
00163                     
00164                     byte buf[] = new byte[bufSize];
00165 
00166                     while(startFlag<300){
00167                         
00168                         int returnSize = audioRec.read(buf,0,buf.length);
00169                         Log.v("returnSize",""+returnSize);
00170                         //if(startFlag > 0){
00171                                  
00172                                         audio_msg = audio_pub.newMessage();
00173                                         ChannelBuffer heapBuffer = buffer(LITTLE_ENDIAN,bufSize);
00174                                         //Log.v("audio2",""+heapBuffer.writableBytes()+","+heapBuffer.isDirect()+","+heapBuffer.order());
00175                                         heapBuffer.writeBytes(buf);
00176                                         
00177                                         //Log.v("heap",hexDump(heapBuffer));
00178                                         
00179                                         audio_msg.setData(heapBuffer);
00180                                         
00181                                         if(startFlag<300) audio_pub.publish(audio_msg); //本当は<300というか無しで
00182                                         //Log.v("audio","published!");
00183                           
00184                         
00185                         //Thread.sleep(20);
00186                         
00187                         
00188                         Log.v("AudioRecord","read:"+buf[0]+","+buf[1]);
00189                     //out.write(buf);
00190                     }
00191                     
00192                     //new!
00193                     Log.v("AudioRecord","stop");
00194                     audioRec.stop();
00195                     out.close();
00196                     out = null;
00197                     addWavHeader();
00198                     Log.v("AudioRecord","success!");
00199 
00200                 
00201                 }catch(Exception e){
00202                         
00203                 }
00204                 }}).start();
00205 
00206         
00207         
00208     }
00209         
00210     //new!
00211  // WAVヘッダをつけて保存
00212  // 各種例外処理略 チェック処理略
00213  public void addWavHeader() {
00214          
00215          try{
00216      // 録音したファイル
00217      File recFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/rec.raw");
00218      // WAVファイル
00219      File wavFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/rec.wav");
00220      // ストリーム
00221      FileInputStream in = new FileInputStream(recFile);
00222      FileOutputStream out = new FileOutputStream(wavFile);
00223      
00224      // ヘッダ作成  サンプルレート8kHz
00225      byte[] header = createHeader(SAMPLING_RATE, (int)recFile.length());
00226      // ヘッダの書き出し
00227      out.write(header);
00228      Log.v("recFile",""+(int)recFile.length());
00229      // 録音したファイルのバイトデータ読み込み
00230      int n = 0,offset = 0;
00231      byte[] buffer = new byte[(int)recFile.length()];
00232      while (offset < buffer.length
00233              && (n = in.read(buffer, offset, buffer.length - offset)) >= 0) {
00234          offset += n;
00235      }
00236      // バイトデータ書き込み
00237      out.write(buffer);
00238       
00239      // 終了
00240      in.close();
00241      out.close();
00242          }catch(IOException e){
00243                  
00244          }
00245  }
00246   
00247     
00248 
00249     public static byte[] createHeader(int sampleRate, int datasize) {
00250         byte[] byteRIFF = {'R', 'I', 'F', 'F'};
00251         byte[] byteFilesizeSub8 = intToBytes((datasize + 36));  // ファイルサイズ-8バイト数
00252         byte[] byteWAVE = {'W', 'A', 'V', 'E'};
00253         byte[] byteFMT_ = {'f', 'm', 't', ' '};
00254         byte[] byte16bit = intToBytes(16);                  // fmtチャンクのバイト数
00255         byte[] byteSamplerate = intToBytes(sampleRate);     // サンプルレート
00256         byte[] byteBytesPerSec = intToBytes(sampleRate * 2);    // バイト/秒 = サンプルレート x 1チャンネル x 2バイト
00257         byte[] bytePcmMono = {0x01, 0x00, 0x01, 0x00};      // フォーマットID 1 =リニアPCM  ,  チャンネル 1 = モノラル
00258         byte[] byteBlockBit = {0x02, 0x00, 0x10, 0x00};     // ブロックサイズ2バイト サンプルあたりのビット数16ビット
00259         byte[] byteDATA = {'d', 'a', 't', 'a'};
00260         byte[] byteDatasize = intToBytes(datasize);         // データサイズ
00261  
00262         ByteArrayOutputStream out = new ByteArrayOutputStream();
00263         try {
00264             out.write(byteRIFF);
00265             out.write(byteFilesizeSub8);
00266             out.write(byteWAVE);
00267             out.write(byteFMT_);
00268             out.write(byte16bit);
00269             out.write(bytePcmMono);
00270             out.write(byteSamplerate);
00271             out.write(byteBytesPerSec);
00272             out.write(byteBlockBit);
00273             out.write(byteDATA);
00274             out.write(byteDatasize);
00275  
00276         } catch (IOException e) {
00277             return out.toByteArray();
00278         }
00279  
00280         return out.toByteArray();
00281     }
00282     
00283     // int型32ビットデータをリトルエンディアンのバイト配列にする
00284     public static byte[] intToBytes(int value) {
00285         byte[] bt = new byte[4];
00286         bt[0] = (byte)(value & 0x000000ff);
00287         bt[1] = (byte)((value & 0x0000ff00) >> 8);
00288         bt[2] = (byte)((value & 0x00ff0000) >> 16);
00289         bt[3] = (byte)((value & 0xff000000) >> 24);
00290         return bt;
00291     }
00292 
00293     @Override
00294         public void onShutdown(Node node) {
00295         Log.v("AudioRecord","stop");
00296         audioRec.stop();
00297         audioRec.release();
00298  
00299     }
00300 
00301     @Override
00302         public void onShutdownComplete(Node node) {
00303     }
00304 
00305     @Override
00306         public void onError(Node node, Throwable throwable) {
00307     }
00308             
00309                         
00310 }


jsk_android_apps
Author(s): Kazuto Murase
autogenerated on Thu Jun 6 2019 18:03:46