Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

java - Why AudioRecord is not recording sound when device fall asleep even when I use WakeLock?

I'm recording the sound from device with AudioRecord and write it to .wav file and I need it to keep recording and writing in file even when the device goes to sleep. So I used wakeLock with PARTIAL_WAKE_LOCK argument. But after the device went asleep AudioRecord keep recording but there is no sound. When I opened a .wav file there is a silent from the moment when device went asleep.

audioRecord.startRecording();
isReading = true;
totalSizeInBytes = 0;        
new Thread(new Runnable() {
        @Override
        public void run() {
            short[] buffer = new short[bufferSize]; //buffer of shorts, getting from audioRecord
            int readCount;
            int state;
            int check = 0;
                        //wakeLock initialization and acquiring
            PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp:RecordWakeLock");
            wakeLock.acquire();
            if (isWavFileCreated) {
                while (isReading) {
                    Log.d(TAG, audioRecord.getRecordingState() + "");
                    readCount = audioRecord.read(buffer, 0, bufferSize);
                    writeWavFile(buffer);
                }
                writeWavFileHeader();
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

audioRecord.getRecordState() always return true. I don't know what'fs the problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should start recording/initialize AudioRecord in independent thread, and start this thread you need from foreground Service. Also right before start of recording change thread priority like in example below:

android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);

AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC,
            sampleRate,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT,
            bufferSize);
record.startRecording();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...