FileOutputStream max_allowed_dequeued_buffers 3 - PullRequest
       8

FileOutputStream max_allowed_dequeued_buffers 3

0 голосов
/ 28 сентября 2018

Когда я пытаюсь использовать FileOutputStream для записи данных в файл, я получаю эту ошибку и не знаю, что с ней делать.Вот class, откуда произошла ошибка.Добавление остальной части программы, чтобы показать, что вызовы process будет слишком длинным, чтобы уместиться здесь.

public class WriterProcessor implements AudioProcessor {
    File output;
    TarsosDSPAudioFormat audioFormat;
    FileOutputStream fos;

    /**
     *
     * @param audioFormat which this processor is attached to
     * @param output randomaccessfile of the output file
     */
    public WriterProcessor(TarsosDSPAudioFormat audioFormat,File output){
        this.output=output;
        this.audioFormat=audioFormat;
        deleteFile();
        openFileStream();
    }
    @Override
    public boolean process(AudioEvent audioEvent) {
        writeIntoOutputfile(audioEvent.getByteBuffer());
        return true;
    }

    @Override
    public void processingFinished() {
        try {
            fos.close();
        } catch (IOException ex) {
        }

        try {
            System.out.println("Buffer size: " + audioFormat.getFrameSize());
            byte[] bytes = new byte[audioFormat.getFrameSize()];


            RandomAccessFile raf = new RandomAccessFile(output.getPath(), "wr");
            raf.read(bytes, 0 ,audioFormat.getFrameSize());


        } catch (Exception ex){

        }
    }


    /**
     * Writes data into file
     * @param data
     */
    private void writeIntoOutputfile(byte[] data) {
        try {
            fos.write(data);
        } catch (IOException ioe) {
            Log.w("Audio processor", "failed writing debug data to file");
            throw new RuntimeException(ioe);
        }
    }

    private void openFileStream() {
        fos = null;
        try {
            fos = new FileOutputStream(output, false);
        } catch (FileNotFoundException e) {
            Log.e("AudioRecorder", e.getMessage());
        }
    }

    private void deleteFile(){
        if (output.exists()) {
            output.delete();
        }
    }

}

Метод process () вызывает writeIntoOutputFile () и обычно эта ошибка происходит от IOException.

09-28 13:54:24.564 19533-19731/ E/[EGL-ERROR]: void __egl_platform_dequeue_buffer(egl_surface*):1851: failed to dequeue buffer from native window 0x98965808; err = -19, buf = 0x0,max_allowed_dequeued_buffers 3
09-28 13:54:24.569 19533-19731/com.starmenew.com E/CameraDeviceGLThread-1: Received exception on GL render thread: 
    java.lang.IllegalStateException: makeCurrent: EGL error: 0x300d
        at android.hardware.camera2.legacy.SurfaceTextureRenderer.checkEglError(SurfaceTextureRenderer.java:544)
        at android.hardware.camera2.legacy.SurfaceTextureRenderer.makeCurrent(SurfaceTextureRenderer.java:525)
        at android.hardware.camera2.legacy.SurfaceTextureRenderer.drawIntoSurfaces(SurfaceTextureRenderer.java:745)
        at android.hardware.camera2.legacy.GLThreadManager$1.handleMessage(GLThreadManager.java:105)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:203)
        at android.os.HandlerThread.run(HandlerThread.java:61)

Возможно, есть способ освободить dequed buffer или я не совсем понимаю эту ошибку.

1 Ответ

0 голосов
/ 07 октября 2018

Вы получаете сообщение об ошибке при попытке выполнить фоновую операцию.Это наиболее вероятно из-за того, что ваше приложение теряет фокус (блокировка экрана или отключение дисплея) во время выполнения этой операции.

  • Если вам требуется, чтобы ваше приложение сохраняло фокус и отображение во время выполнения фоновой операциипопробуйте добавить разрешение блокировки пробуждения.От https://developer.android.com/training/scheduling/wakelock:

    public class MainActivity extends Activity {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
      }
    }
    
  • Если вы пытаетесь выполнить асинхронную фоновую операцию, такую ​​как обработка звука и запись файла данных, попробуйте AsyncTask :

    private class WriteIntoOutputfileTask extends AsyncTask <TarsosDSPAudioFormat, File, AudioEvent, Integer, Long> {
    
        protected Long doInBackground(TarsosDSPAudioFormat audioFormat, File output, AudioEvent audioEvent) {
            long processedFiles = 0;
            publishProgress(0);
            WriterProcessor myWriterProcessor = new WriterProcessor(audioFormat, output);
            myWriterProcessor.process(audioEvent);
            publishProgress(100);
            processedFiles = 1;
            return processedFiles;
        }
    
        protected void onProgressUpdate(Integer... progress) {
            setProgressPercent(progress[0]);
        }
    
        protected void onPostExecute(Long result) {
            showDialog(result + " streams processed successfully");
        }
    
    }
    // Then run this code to start the task:
    new WriteIntoOutputfileTask().execute(audioFormat, output, audioEvent);
    

Это, конечно, только подтверждение концепции.Для фактической реализации вы должны переписать ваш WriterProcessor как AsyncTask.Тогда ваш метод public boolean process(AudioEvent audioEvent) будет частью метода doInBackground расширения AsyncTask.

Для более запутанных асинхронных операций вы можете обратиться к IntentService или TaskScheduler .

Если вы хотите, чтобы ваша задача была синхронной (из вашего кода это не так), найдите альтернативу, которая лучше всего соответствует вашим потребностям, из DownloadManager или SyncAdapter

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...