除非重新启动,否则我的应用程序不会创建新文件

时间:2019-03-01 08:05:59

标签: java android

该应用程序记录音频。每次执行检查时,如果要创建一个文件,它都不会用相同的名称替换以前的文件,而是创建一个新文件,而在文件名中添加“(number)”。

这是它的代码:

    mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
    int entryNumber = 1;
    File mFile = new File(mFileName + "/Recording (" + String.valueOf(entryNumber) + ")" + ".mp3");
    while (mFile.exists()) {
        entryNumber++;
        mFile = new File(mFileName + "/Recording (" + String.valueOf(entryNumber) + ")" + ".mp3");
    }
    this.mFileName = mFile.getAbsolutePath();

记录过程:

                    mRecorder = new MediaRecorder();
                    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                    mRecorder.setOutputFile(mFileName);
                    try {
                        mRecorder.prepare();
                    } catch (IOException e) {
                        Log.e(LOG_TAG, "prepare() failed");
                    }
                    mRecorder.start();
                    isRecording = true;
                    recordBtn.setText("Stop");
                    Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();

我发现了一个错误。该应用仅在退出并重新启动时才会创建新文件。

如果用户继续录制声音,则该应用不会创建新文件,而是会覆盖之前的文件来替换它。应该总是在录制时创建一个新文件。

完整的项目代码:

package com.android.greg.garec;

import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class MainActivity extends AppCompatActivity {

    private Button recordBtn, playBtn;
    private MediaRecorder mRecorder;
    private MediaPlayer mPlayer;
    private static final String LOG_TAG = MainActivity.class.getSimpleName();
    private static String mFileName = null;
    public static final int REQUEST_AUDIO_PERMISSION_CODE = 1;

    boolean isRecording = false;
    boolean isPlaying = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recordBtn = findViewById(R.id.btnRecord);
        playBtn = findViewById(R.id.btnPlay);
        playBtn.setEnabled(false);
        playBtn.setVisibility(View.INVISIBLE);

////////////////////////////////////////////////////////////////////////////////////////////////////////

        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        int entryNumber = 1;
        File mFile = new File(mFileName + "/Recording_" + String.valueOf(entryNumber) + ".mp3");
        while (mFile.exists()) {
            // File exists, just increment number
            entryNumber++;
        }

        // Only create the file when it does not exist
        mFile = new File(mFileName + "/Recording_" + String.valueOf(entryNumber) + ".mp3");
        try {
            mFile.createNewFile();
        }
        catch (IOException e) {
        e.printStackTrace();
        }
        this.mFileName = mFile.getAbsolutePath();

////////////////////////////////////////////////////////////////////////////////////////////////////////

        //Record button actions
        recordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRecording) {
                    playBtn.setEnabled(true);
                    playBtn.setVisibility(View.VISIBLE);
                    mRecorder.stop();
                    mRecorder.release();
                    mRecorder = null;
                   // Toast.makeText(getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
                    isRecording = false;
                    recordBtn.setText("Record");
                } else {
                    if (CheckPermissions()) {
                        playBtn.setEnabled(false);
                        playBtn.setVisibility(View.INVISIBLE);
                        mRecorder = new MediaRecorder();
                        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                        mRecorder.setOutputFile(mFileName);
                        try {
                            mRecorder.prepare();
                        } catch (IOException e) {
                            Log.e(LOG_TAG, "prepare() failed");
                        }
                        mRecorder.start();
                        isRecording = true;
                        recordBtn.setText("Stop");
                     //   Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();
                    } else {
                        RequestPermissions();
                    }
                }
            }
        });

        //Play button actions
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isPlaying) {
                    mPlayer.release();
                    mPlayer = null;
                    recordBtn.setEnabled(true);
                    playBtn.setEnabled(true);
                  //  Toast.makeText(getApplicationContext(), "Playing Audio Stopped", Toast.LENGTH_SHORT).show();
                    isPlaying=false;
                    playBtn.setText("Play");
                } else {
                    recordBtn.setEnabled(true);
                    playBtn.setEnabled(true);
                    mPlayer = new MediaPlayer();
                    try {
                        mPlayer.setDataSource(mFileName);
                        mPlayer.prepare();
                        mPlayer.start();
                   //     Toast.makeText(getApplicationContext(), "Recorded playback started", Toast.LENGTH_LONG).show();

                        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {
                                isPlaying = false;
                          //      Toast.makeText(MainActivity.this, "Recorded playback finished", Toast.LENGTH_SHORT).show();
                                playBtn.setEnabled(true);
                                playBtn.setVisibility(View.VISIBLE);
                                playBtn.setText("Play");
                            }
                        });
                    } catch (IOException e) {
                        Log.e(LOG_TAG, "prepare() failed");
                    }
                    isPlaying=true;
                    playBtn.setText("Stop");
                }
            }
        });
    }

    //Permission checks - requests
    @Override
    public void onRequestPermissionsResult ( int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode) {
            case REQUEST_AUDIO_PERMISSION_CODE:
                if (grantResults.length > 0) {
                    boolean permissionToRecord = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean permissionToStore = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    boolean permissionToRead = grantResults[2] == PackageManager.PERMISSION_GRANTED;
                    if (permissionToRecord && permissionToStore && permissionToRead) {
                        Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    public boolean CheckPermissions () {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
        int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
        int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
        return (result == PackageManager.PERMISSION_GRANTED) && (result1 == PackageManager.PERMISSION_GRANTED) && (result2 == PackageManager.PERMISSION_GRANTED);
    }

    private void RequestPermissions () {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, REQUEST_AUDIO_PERMISSION_CODE);
    }

}

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnRecord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="120dp"
        android:layout_marginEnd="135dp"
        android:layout_marginBottom="160dp"
        android:text="Record" />

    <Button
        android:id="@+id/btnPlay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="100dp"
        android:layout_marginEnd="135dp"
        android:layout_marginBottom="100dp"
        android:text="Play" />

</RelativeLayout>

清单文件:

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

1 个答案:

答案 0 :(得分:0)

new File()只是创建一个新对象,而不是文件系统上的实际文件。

使用createNewFile()创建一个空文件(documentation):

File file = new File(mFileName + "/Recording (" + String.valueOf(entryNumber) + ")" + ".mp3");
if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
} 

在不替换现有文件的情况下应该起作用的示例:

mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
    int entryNumber = 1;
    File mFile = new File(mFileName + "/Recording (" + String.valueOf(entryNumber) + ")" + ".mp3");
    while (mFile.exists()) {
        // File exists, just increment number
        entryNumber++;
    }
    // Only create the file when it does not exists
    mFile = new File(mFileName + "/Recording (" + String.valueOf(entryNumber) + ")" + ".mp3");
    try {
        mFile.createNewFile()
    }
    catch (IOException e) {
        e.printStacjTrace();
    }
    this.mFileName = mFile.getAbsolutePath();

希望有帮助!