设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 1786|回复: 5

Android Audio Recording Tutorial

  [复制链接]
发表于 2010-11-17 14:32:39 | 显示全部楼层 |阅读模式
After many hours of trying to record audio on my Google Android device, I’ve finally arrived at a workable solution.  There were a few bumps along the way besides the horribly out of date MediaRecorder documentation, which was sorely lacking details.  For one, I could only get audio to record to the SD card.  Additionally, the directory being recorded to must already exist before attempting to record to it.  Without further ado, here is a complete example for recording audio on the Android via the MediaRecorder API:

package com.benmccann.android.hello;

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;
import android.os.Environment;

/**
* @author <a href="http://www.benmccann.com">Ben McCann</a>
*/
public class AudioRecorder {

  final MediaRecorder recorder = new MediaRecorder();
  final String path;

  /**
   * Creates a new audio recording at the given path (relative to root of SD card).
   */
  public AudioRecorder(String path) {
    this.path = sanitizePath(path);
  }

  private String sanitizePath(String path) {
    if (!path.startsWith("/")) {
      path = "/" + path;
    }
    if (!path.contains(".")) {
      path += ".3gp";
    }
    return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
  }

  /**
   * Starts a new recording.
   */
  public void start() throws IOException {
    String state = android.os.Environment.getExternalStorageState();
    if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
        throw new IOException("SD Card is not mounted.  It is " + state + ".");
    }

    // make sure the directory we plan to store the recording in exists
    File directory = new File(path).getParentFile();
    if (!directory.exists() && !directory.mkdirs()) {
      throw new IOException("Path to file could not be created.");
    }

    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(path);
    recorder.prepare();
    recorder.start();
  }

  /**
   * Stops a recording that has been previously started.
   */
  public void stop() throws IOException {
    recorder.stop();
    recorder.release();
  }

}

http://www.benmccann.com/dev-blog/android-audio-recording-tutorial/
 楼主| 发表于 2010-11-17 14:33:52 | 显示全部楼层
#
dragonksn said,

April 1, 2009 at 9:30 pm

Hello, I’m a new comer to Android and I am a bit poor in Java.
I want to record a sound in my Android Emulator, so I copied your code(change the package name a bit) and Run. But it says “The Application Android, Application(process AndroidTest.package) has stopped unexpectedly. Please try again”. “Android, Application” is my app name and “AndroidTest.package” is my package name.

Can u tell me why it can’t be run? I’ve tried to change the code to make it run, but I can’t. Please help me! I must be able to get a audio stream into Android to test with my other urgent end year project.

Thanks in advanced :)
#
david said,

April 2, 2009 at 11:06 pm

hi Ben, I encountered the same problem on G1 as dragonksn’s when using your code . “The application audiorecorder(process com.david.android.audiorecorder) has stopped unexpectedly. Please try again”.

My audiorecoder class looks like as:

import android.app.Activity;
import android.os.Bundle;
//importing yours


public class audiorecorder extends Activity {
//then following your codes

}

Below is the Logcat info:

D/AndroidRuntime( 815): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime( 815): CheckJNI is ON
D/AndroidRuntime( 815): — registering native functions —
I/jdwp ( 815): received file descriptor 25 from ADB
I/ActivityManager( 56): Starting activity: Intent { flags=0×10000000 comp={com.david.android.audiorecorder/com.david.android.audiorecorder.audiorecorder} }
I/ActivityManager( 56): Start proc com.david.android.audiorecorder for activity com.david.android.audiorecorder/.audiorecorder: pid=824 uid=10040 gids={}
D/AndroidRuntime( 815): Shutting down VM
D/dalvikvm( 815): DestroyJavaVM waiting for non-daemon threads to exit
D/dalvikvm( 815): DestroyJavaVM shutting VM down
D/dalvikvm( 815): HeapWorker thread shutting down
D/dalvikvm( 815): HeapWorker thread has shut down
D/jdwp ( 815): JDWP shutting down net…
D/jdwp ( 815): +++ peer disconnected
I/dalvikvm( 815): Debugger has detached; object registry had 1 entries
D/dalvikvm( 815): VM cleaning up
D/dalvikvm( 815): LinearAlloc 0×0 used 594756 of 4194304 (14%)
I/jdwp ( 824): received file descriptor 10 from ADB
D/dalvikvm( 824): newInstance failed: no ()
D/AndroidRuntime( 824): Shutting down VM
W/dalvikvm( 824): threadid=3: thread exiting with uncaught exception (group=0x4000fe68)
E/AndroidRuntime( 824): Uncaught handler: thread main exiting due to uncaught exception
E/AndroidRuntime( 824): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.david.android.audiorecorder/com.david.android.audiorecorder.audiorecorder}: java.lang.InstantiationException: com.david.android.audiorecorder.audiorecorder
E/AndroidRuntime( 824): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2082)
E/AndroidRuntime( 824): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2172)
E/AndroidRuntime( 824): at android.app.ActivityThread.access$1800(ActivityThread.java:112)
E/AndroidRuntime( 824): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1586)
E/AndroidRuntime( 824): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 824): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 824): at android.app.ActivityThread.main(ActivityThread.java:3790)
E/AndroidRuntime( 824): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 824): at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime( 824): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
E/AndroidRuntime( 824): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:503)
E/AndroidRuntime( 824): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 824): Caused by: java.lang.InstantiationException: com.david.android.audiorecorder.audiorecorder
E/AndroidRuntime( 824): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime( 824): at java.lang.Class.newInstance(Class.java:1458)
E/AndroidRuntime( 824): at android.app.Instrumentation.newActivity(Instrumentation.java:1097)
E/AndroidRuntime( 824): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
E/AndroidRuntime( 824): … 11 more
I/Process ( 56): Sending signal. PID: 824 SIG: 3
I/dalvikvm( 824): threadid=7: reacting to signal 3
I/dalvikvm( 824): Wrote stack trace to ‘/data/anr/traces.txt’
W/InputManagerService( 56): Starting input on non-focused client android.view.inputmethod.InputMethodManager$1@43704540 (uid=1000 pid=56)
W/InputManagerService( 56): Ignoring focus gain of: android.view.inputmethod.InputMethodManager$1@43704540
W/ActivityManager( 56): Launch timeout has expired, giving up wake lock!
W/ActivityManager( 56): Activity idle timeout for HistoryRecord{43852e68 {com.david.android.audiorecorder/com.david.android.audiorecorder.audiorecorder}}
D/dalvikvm( 100): GC freed 1763 objects / 93784 bytes in 135ms
I/Process ( 824): Sending signal. PID: 824 SIG: 9
I/ActivityManager( 56): Process com.david.android.audiorecorder (pid 824) has died.
D/InputManagerService( 56): hide the small icon for the input method
V/ActivityThread( 100): Resuming ActivityRecord{436cc620 token=android.os.BinderProxy@436cc0b0 {com.android.launcher/com.android.launcher.Launcher}} with isForward=false

I’m sorry for the mess. Could your please help me figure out what’s the reason caused this issue? Thanks a lot.

david
 楼主| 发表于 2010-11-17 14:40:43 | 显示全部楼层
dragonksn, david:
Hi, the cause is that the source above is not an android *application*, just a helper class. So it just can’t run by itself.
You have to do something like this:
public class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                final AudioRecorder recorder = new AudioRecorder(“/audiometer/temp”);
                recorder.start();
                //….wait a while
                recorder.stop();
    }
}

my stop method calls release, which is why you can’t call stop and then start again.  I believe if you take out the call to release you will be able to call start again.

  •                                 Sisi said,                               
                            July 28, 2009                        at 6:43 am                                       
                                    Hello,
    i try this application, but it’s not playing.
    I think my path is not good… but i don’t know how i have to change!
    Here is my code..it’s a little bit long, because i also use Button. I can’t playing what i have recording!
    package com.swyx.AudioRecording2;
    import java.io.IOException;
    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;
            public class Record extends Activity {
                    //Wahrscheinlich ist den angegebenen Pfad nicht richtig! Nur wie gebe ich richtig ein?
            /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                //System.out.print(“bis hier geht”);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            /*Erstelle ein neues Objekt von Typ Button,
            das aktiviert wird sobald es geklickt wird*/
            Button btn1 = (Button)findViewById(R.id.record);
            btn1.setOnClickListener(btnListener1);
            Button btn2 = (Button)findViewById(R.id.stop);
            btn2.setOnClickListener(btnListener2);
            Button btn3 = (Button)findViewById(R.id.play);
            btn3.setOnClickListener(btnListener3);
      }
        //folgendes passiert, wenn auf btn1 geklickt wird
        private OnClickListener btnListener1 = new OnClickListener()
        {
            public void onClick(View v)
            {
                    final AudioRecorder2 recorder = new AudioRecorder2(“C:/Bochum”);
                    try {
                                    recorder.start();
                            } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                            }
                    //….wait a while
                    try {
                                    recorder.stop();
                            } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                            }
            }
        };  
      //folgendes passiert, wenn auf btn2 geklickt wird
        private OnClickListener btnListener2 = new OnClickListener()
        {
            public void onClick(View v)
            {
               MediaPlayer mp =  new MediaPlayer();
                    Toast.makeText(getBaseContext(),
                        “Hello, please stop!” + mp.isPlaying(),
                        Toast.LENGTH_LONG).show();
              /*
                try {
                                    recorder.stop();
                            } catch (IOException e) {
                            }*/
            }
        };   
      //folgendes passiert, wenn auf btn3 geklickt wird
        private OnClickListener btnListener3 = new OnClickListener()
        {
            public void onClick(View v)
            {                       
             MediaPlayer mp = new MediaPlayer();  
             try {
                            mp.setDataSource(“C:/Bochum”);
                    } catch (IllegalArgumentException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
             try {
                            mp.prepare();
                    } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
             mp.start();
             Toast.makeText(getBaseContext(),
                     “Hello, please play!” +” is playing?: “+ mp.isPlaying(),
                     Toast.LENGTH_LONG).show();
            }
        };
    }
    Thanks for your help! I’m desesperate!
    Sisi


Sisi,
You can’t record to C:\ because that’s a Windows path.  Android uses Linux type paths.  Try recording to something like “test/tmp.3gp” instead.


   
发表于 2011-6-7 01:51:09 | 显示全部楼层
非常好的东西,很给力!!
哈哈




MillashaMillashaMillasha
发表于 2011-10-30 16:19:47 | 显示全部楼层
大家什么看法?我先支持
发表于 2011-12-1 14:40:12 | 显示全部楼层
楼主高人啊,我先收藏了












性吧最新网站地址:www.3yy8.com

性吧最新网站网址:www.3yy8.com

国内最为掩蔽的一夜站地址:www.3yy8.com

现在开放免费注册, 史上最强的集合!!所有门事放 件大 送!!!! [800M]

松岛枫.苍井空.av种子全集打包下载.. [AVI/89m]

“美空门”上海美空模特徐莹自拍艳照347P高清完整版,免费下载

性吧春暖花开,入口地址:www.3yy8.com

发表于 2012-1-13 08:05:55
先顶后看~~












北京商标
支持 反对

您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-8-26 13:52 , Processed in 0.016034 second(s), 17 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表