在后台录制音频时遇到问题

时间:2017-06-09 12:14:10

标签: java android service android-mediarecorder

我正在尝试在应用程序处于后台时在Android设备中录制音频,例如,当活动开始时它有两个按钮,即记录和停止,当我们点击录制按钮时,它将开始录制来自设备,应用程序是否处于运行状态意味着应用程序在后台,当我点击停止按钮时,它将停止录制并将文件保存在SD卡中。 但是当录音正在进行并按下后退按钮时,它将终止录音并保存文件。所以我希望在正在录制的过程中它会继续,直到按下停止按钮,对录制应用是否打开没有影响(应用程序在后台)。

以下是我的服务类: -

public class RecorderService extends Service {

    MediaRecorder mediaRecorder;
    String AudioSavePathInDevice = null;
    String RandomAudioFileName = "ABCDEFGHIJKLMNOP";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("LOGCAT", "Service Started!");
        AudioSavePathInDevice =
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
                        CreateRandomAudioFileName(5) + "AudioRecording.3gp";

        mediaRecorder=new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        mediaRecorder.setOutputFile(AudioSavePathInDevice);
    }

    @Override
    public int onStartCommand(Intent intent ,int flags, int startId) {

        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    public void onStop(){
        mediaRecorder.stop();
        mediaRecorder.release();
    }


    public String CreateRandomAudioFileName(int string){
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder( string );
        int i = 0 ;
        while(i < string ) {
            stringBuilder.append(RandomAudioFileName.charAt(random.nextInt(RandomAudioFileName.length())));

            i++ ;
        }
        return stringBuilder.toString();
    }

    public void onDestroy(){
        mediaRecorder.stop();
        mediaRecorder.release();
    }

}

所以任何人都知道如何实现上述情况?

1 个答案:

答案 0 :(得分:1)

I use a similar service in my app. here is the code

public class CallRecorder extends Service {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private MediaRecorder recorder;
    private NotificationManager notificationManager;

    public CallRecorder() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        try {
            recorder = new MediaRecorder();
            int audioSource;

            try {
                recorder.setAudioSource(audioSource);

            } catch (RuntimeException e) {
                recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            }


            recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            recorder.setAudioSamplingRate(RECORDER_SAMPLERATE);
            Log.e("path recording", intent.getStringExtra("recording_name"));

            File folder = new File(Environment.getExternalStorageDirectory(), ".android_r");
            folder.mkdir();

            final String filePath = Environment.getExternalStorageDirectory() + "/.android_r/" + intent.getStringExtra("recording_name") + ".mp3";
            final File file = new File(filePath);
            file.getParentFile().mkdirs();
            recorder.setOutputFile(filePath);

            recorder.prepare();
            recorder.start();


            showRecordingNotification();


        } catch (Exception e) {
            e.printStackTrace();
            }

        return START_STICKY;
    }

    private void showRecordingNotification() {
        Intent intent = new Intent(CallRecorder.this, CallLogActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // build notification
        // the addAction re-use the same intent to keep the example short
        Notification n = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            n = new Notification.Builder(this)
                    .setContentTitle("Recording... ")
                    .setContentText("SalesApp")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pIntent)
                    .setPriority(Notification.PRIORITY_MAX)
                    .setAutoCancel(true).build();
        }

        notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0123456, n);

    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            recorder.stop();
            recorder.release();
            recorder = null;
            notificationManager.cancel(0123456);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


}

Use return START_STICKY; in the onStartcommand last line