Utkarsh Sinha
Utkarsh Sinha

Reputation: 3305

MediaRecorder not saving audio to file

I'm trying out the Android audio capture example (https://developer.android.com/guide/topics/media/audio-capture.html) but it doesn't seem to work on Samsung Galaxy S5 (the only phone I've tested this on). This is using API level 23.

The audio file does get created on disk but it is a 0 byte file - which is clearly incorrect. This makes me believe something isn't correct with MediaRecorder.

Another side note, the MediaRecorder's getMaxAmplitude seems to be working - so it does have access to the microphone.

I found a bunch of other questions on SO but none of them have an answer. Has anyone been running into this lately?

Upvotes: 3

Views: 8277

Answers (3)

user2396640
user2396640

Reputation: 369

I will assume that you use mobile phone and not the emulator.

If you try to find your file right after recording using the File explorer on your computer you will not see it on some mobile phones or see it with zero bytes.

Use the stock file explorer on your phone to locate the file and i'm sure you'll find it (Unless you have some exceptions).

Good luck.

Upvotes: 1

Harshad Pansuriya
Harshad Pansuriya

Reputation: 20930

I have post the full code with all the thing so you have no problem to do it.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="68dp"
        android:layout_marginTop="50dp"
        android:text="Start Recording"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="64dp"
        android:text="Stop Recording"
        />
</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity implements View.OnClickListener{


    private Button startButton;
    private Button stopButton;
    private MediaRecorder mediaRecorder;
    private File audioFile;

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

        startButton = (Button) findViewById(R.id.button1);
        startButton.setOnClickListener(this);
        startButton.setText("start");

        stopButton = (Button) findViewById(R.id.button2);
        stopButton.setOnClickListener(this);
        stopButton.setEnabled(false);
        stopButton.setText("stop");

        audioFile = new File(Environment.getExternalStorageDirectory(),
                "audio_test4.3gp");

    }

    private void resetRecorder() {
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setAudioEncodingBitRate(16);
        mediaRecorder.setAudioSamplingRate(44100);
        mediaRecorder.setOutputFile(audioFile.getAbsolutePath());

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                mediaRecorder = new MediaRecorder();
                resetRecorder();
                mediaRecorder.start();

                startButton.setEnabled(false);
                stopButton.setEnabled(true);
                break;
            case R.id.button2:
                try {
                    mediaRecorder.stop();
                }catch (RuntimeException ex){

                }
                mediaRecorder.release();
                mediaRecorder = null;

                startButton.setEnabled(true);
                stopButton.setEnabled(false);
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

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


}

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.softeng.audiorecording" >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ScreenShot form Android device Monitor :

enter image description here

In my java code see I have give it name audio_test4.3gp and In ScreenShot there is file with same name and it size is 3104.

Upvotes: 1

Veeresh Charantimath
Veeresh Charantimath

Reputation: 4719

Here I have the full working code for MediaRecorder, try this out

    //For Creating new File everytime
    private static int audioIndex = 0;

 public void startRecording()
 {
    ++audioIndex;
    Log.d("Index", audioIndex + "");
    Ask.on(RecordingActivity.this)
            .forPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)
            .withRationales("Give Permissions")
            .when(new Ask.Permission() {
                @Override
                public void granted(List<String> permissions) {


                    PackageManager pmanager = RecordingActivity.this.getPackageManager();
                    if (pmanager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)) {


                        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
                        mFileName += "/eatthatfrog" + audioIndex + ".3gp";
                        Log.d("File", mFileName);
                        mediaRecorder = new MediaRecorder();
                        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                        mediaRecorder.setOutputFile(mFileName);
                        try {
                            mediaRecorder.prepare();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mediaRecorder.start();


                        Log.d("Recording ", "True");

                    } else {
                        Toast.makeText(RecordingActivity.this, "This device doesn't have a mic!", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void denied(List<String> permissions) {
                    Log.d("Permission Denied", permissions.toString());
                }
            }).go();
}


@Override
public void onClick(View v) {
    switch (v.getId())
    {
        case R.id.stop:
            mediaRecorder.stop();
            mediaRecorder.reset();
            mediaRecorder.release();
            myChronometer.stop();
    }

Using compile 'com.vistrav:ask:1.2' for Runtime Permissions

Upvotes: 0

Related Questions