0

I found a java class for help to record and stream data immediately :

/*
 * Thread to manage live recording/playback of voice input from the device's microphone.
 */
private class Audio extends Thread
{ 
    private boolean stopped = false;

    /**
     * Give the thread high priority so that it's not canceled unexpectedly, and start it
     */
    private Audio()
    { 
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
        start();
    }

    @Override
    public void run()
    { 
        Log.i("Audio", "Running Audio Thread");
        AudioRecord recorder = null;
        AudioTrack track = null;
        short[][]   buffers  = new short[256][160];
        int ix = 0;

        /*
         * Initialize buffer to hold continuously recorded audio data, start recording, and start
         * playback.
         */
        try
        {
            int N = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);
            recorder = new AudioRecord(AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10);
            track = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, 
                    AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10, AudioTrack.MODE_STREAM);
            recorder.startRecording();
            track.play();
            /*
             * Loops until something outside of this thread stops it.
             * Reads the data from the recorder and writes it to the audio track for playback.
             */
            while(!stopped)
            { 
                Log.i("Map", "Writing new data to buffer");
                short[] buffer = buffers[ix++ % buffers.length];
                N = recorder.read(buffer,0,buffer.length);
                track.write(buffer, 0, buffer.length);
            }
        }
        catch(Throwable x)
        { 
            Log.w("Audio", "Error reading voice audio", x);
        }
        /*
         * Frees the thread's resources after the loop completes so that it can be run again
         */
        finally
        { 
            recorder.stop();
            recorder.release();
            track.stop();
            track.release();
        }
    }

    /**
     * Called from outside of the thread in order to stop the recording/playback loop
     */
    private void close()
    { 
         stopped = true;
    }

}

source here : Android: Need to record mic input

I want to use this class for my application, but I don't know how it works. I want to record and stream data in the same time from my main activity.

EDIT 1 : I call the object here :

public static class TypingDialogFragment extends DialogFragment {

        EditText cmdLine;
        static MainActivity parentActivity;
        static ThreadConnected cmdThreadConnected;
        static int a=0;
        static int type1=0;
        static int type2=0;
        static int run_voice=0; 
        static int run_voice1=0; 

        static byte[] memory_freq="100".getBytes(); 
        static byte[] gain_rf="42".getBytes(); 
        static byte[] gain_if="47".getBytes(); 
        static byte[] gain_bb="0".getBytes();

         byte[] NewLine = "\n".getBytes();
         byte[] kill="killall python".getBytes();

         byte[] run_emetteur="DISPLAY=:0 python emetteur.py --freq ".getBytes();
         byte[] run_receiver="DISPLAY=:0 python receiver.py --freq ".getBytes();
         byte[] end_command = "&".getBytes(); 
         byte[] freq_Mhz = "e6 ".getBytes();
         byte[] RF_text=" --RF ".getBytes();
         byte[] IF_text=" --IF ".getBytes();
         byte[] BB_text=" --BB ".getBytes();

           // MediaPlayer
        private String OUTPUT_FILE;
        private boolean stopped = false;
        MediaPlayer mediaPlayer;
        MediaRecorder mediaRecorder;
        File outFile;

        // Image button
        ImageButton send_voice; 

        Chronometer myChrono;
        ProgressBar progressBar;

        Audio record_song; // My VARIABLE -------------------------------------------------------------------------------------------


        static TypingDialogFragment newInstance(MainActivity parent, ThreadConnected thread, int type){
        type1=type;
        parentActivity = parent;
        cmdThreadConnected = thread;
        TypingDialogFragment f = new TypingDialogFragment();

        return f;
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            getDialog().setTitle("Cmd Line");
            getDialog().setCanceledOnTouchOutside(false);
            final View typingDialogView = inflater.inflate(R.layout.typing_layout, container, false);
            ImageView imgCleaarCmd = (ImageView)typingDialogView.findViewById(R.id.clearcmd);

            // Audio
           /* OUTPUT_FILE= Environment.getExternalStorageDirectory()+ "/audiorecord.wav";
            outFile=new File (OUTPUT_FILE);*/

            record_song=new Audio(); // ERROR HERE --------------------------------------------------------------------------------

            cmdLine = (EditText)typingDialogView.findViewById(R.id.cmdline);
            myChrono=(Chronometer) getActivity().findViewById(R.id.chronometer1);
            send_voice=(ImageButton) getActivity().findViewById(R.id.send_voice1);
            progressBar=(ProgressBar) getActivity().findViewById(R.id.progressBar1);

            Button bouton1 = (Button)typingDialogView.findViewById(R.id.button1);
            Button bouton2=(Button)typingDialogView.findViewById(R.id.button2);
            Button bouton3 = (Button)typingDialogView.findViewById(R.id.button3);
            Button bouton4 = (Button)typingDialogView.findViewById(R.id.button4);
            final ImageButton send_voice=(ImageButton)getActivity().findViewById(R.id.send_voice1);

            imgCleaarCmd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            if(type1==1) 
            {
                bouton1.setText("STOP");
                bouton2.setText("OFF");
                bouton3.setText("Reset");
                bouton4.setText("Enter");
            }

            if(type1==2) 
            {
                bouton1.setText("TX");
                bouton2.setText("RX");
                bouton3.setText("Clear");
                bouton4.setText("Enter");
            }

            if(type1==3) 
            {
                bouton1.setText("Gain RF");
                bouton2.setText("Gain IF");
                bouton3.setText("Gain BB");
                bouton4.setText("Enter");
            }

            bouton1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type1==1)
                    {
                        cmdLine.setText("killall python");

                    }
                    if (type1==2)
                    {
                        cmdLine.setHint("// Partie Emission");
                        a=1;
                    }
                    if (type1==3)
                    {
                        type2=1;
                        cmdLine.setHint("// Gain RF");

                    }
                }
            });

            bouton2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type1==1)
                    {
                        cmdLine.setText("sudo poweroff");

                    }
                    if (type1==2)
                    {
                        cmdLine.setHint("// Partie Reception");
                        a=2;
                    }
                    if (type1==3)
                    {
                        byte[] bytesToSend = cmdLine.getText().toString().getBytes();

                        if (bytesToSend!=null)
                        {
                            type2=2;
                            cmdLine.setHint("// Gain IF");
                        }
                    }
                }
            });

            bouton3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type1==1)
                    {
                        cmdLine.setText("sudo reboot");
                        a=1;
                    }
                    if (type1==2)
                    {
                        body.setText("");
                    }
                    if (type1==3)
                    {
                        byte[] bytesToSend = cmdLine.getText().toString().getBytes();

                        if (bytesToSend!=null)
                        {
                            type2=3;
                            cmdLine.setHint("// Gain BB");
                        }
                    }
                }
            });

            bouton4.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(cmdThreadConnected!=null){

                        if (type1==1)
                        // Command terminal
                        {
                            byte[] bytesToSend = cmdLine.getText().toString().getBytes();
                            cmdThreadConnected.write(bytesToSend);
                            byte[] NewLine = "\n".getBytes();
                            cmdThreadConnected.write(NewLine);
                        }

                        if (type1==2) // FREQUENCE lancement de la partie réception ou émission
                        {
                            if (a==1)
                            {
                                byte[] bytesToSend = cmdLine.getText().toString().getBytes();
                                memory_freq=bytesToSend;
                                cmdThreadConnected.write(kill);
                                cmdThreadConnected.write(NewLine);
                                cmdThreadConnected.write(run_emetteur);
                                cmdThreadConnected.write(memory_freq);
                                cmdThreadConnected.write(freq_Mhz);
                                cmdThreadConnected.write(RF_text);
                                cmdThreadConnected.write(gain_rf);
                                cmdThreadConnected.write(IF_text);
                                cmdThreadConnected.write(gain_if);
                                cmdThreadConnected.write(BB_text);
                                cmdThreadConnected.write(gain_bb);
                                cmdThreadConnected.write(end_command);
                                cmdThreadConnected.write(NewLine);
                            }

                            if (a==2)
                            {
                                byte[] bytesToSend = cmdLine.getText().toString().getBytes();
                                memory_freq=bytesToSend;
                                cmdThreadConnected.write(kill);
                                cmdThreadConnected.write(NewLine);
                                cmdThreadConnected.write(run_receiver);
                                cmdThreadConnected.write(memory_freq);
                                cmdThreadConnected.write(freq_Mhz);
                                cmdThreadConnected.write(RF_text);
                                cmdThreadConnected.write(gain_rf);
                                cmdThreadConnected.write(IF_text);
                                cmdThreadConnected.write(gain_if);
                                cmdThreadConnected.write(BB_text);
                                cmdThreadConnected.write(gain_bb);
                                cmdThreadConnected.write(end_command);
                                cmdThreadConnected.write(NewLine);
                            }

                        }

                        if(type1==3)
                        {
                           byte[] bytesToSend = cmdLine.getText().toString().getBytes();

                            if (type2==1)gain_rf=bytesToSend;
                            if (type2==2)gain_if=bytesToSend;
                            if (type2==3)gain_bb=bytesToSend;

                           dismiss();
                        }
                    }
                }
            });

            send_voice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (run_voice==0)
                    {
                        try{
                            beginRecording();
                            send_voice.setColorFilter(Color.RED);
                            progressBar.setVisibility(View.VISIBLE);
                            myChrono.setBase(SystemClock.elapsedRealtime());
                            myChrono.start();
                            cmdThreadConnected.write(kill);
                            cmdThreadConnected.write(NewLine);
                            cmdThreadConnected.write(run_emetteur);
                            cmdThreadConnected.write(memory_freq);
                            cmdThreadConnected.write(freq_Mhz);
                            cmdThreadConnected.write(RF_text);
                            cmdThreadConnected.write(gain_rf);
                            cmdThreadConnected.write(IF_text);
                            cmdThreadConnected.write(gain_if);
                            cmdThreadConnected.write(BB_text);
                            cmdThreadConnected.write(gain_bb);
                            cmdThreadConnected.write(end_command);
                            cmdThreadConnected.write(NewLine);
                           }catch (IOException ex)
                        {
                            // if not working
                        }
                        run_voice1=1;
                    }
                    if (run_voice==1)
                    {
                        stopRecording();
                        send_voice.setColorFilter(Color.BLACK);
                        progressBar.setVisibility(View.INVISIBLE);
                        myChrono.stop();
                        cmdThreadConnected.write(kill);
                        cmdThreadConnected.write(NewLine);
                        cmdThreadConnected.write(run_receiver);
                        cmdThreadConnected.write(memory_freq);
                        cmdThreadConnected.write(freq_Mhz);
                        cmdThreadConnected.write(RF_text);
                        cmdThreadConnected.write(gain_rf);
                        cmdThreadConnected.write(IF_text);
                        cmdThreadConnected.write(gain_if);
                        cmdThreadConnected.write(BB_text);
                        cmdThreadConnected.write(gain_bb);
                        cmdThreadConnected.write(end_command);
                        cmdThreadConnected.write(NewLine);

                        run_voice1=0;
                    }
                    run_voice=run_voice1;
                }

                private void ditchMediaplayer()
                {
                    if (mediaRecorder!=null)mediaRecorder.release();
                    try
                    {
                        mediaPlayer.release();
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }

                private void beginRecording()throws IOException
                {

                 /*   ditchMediaplayer();

                    if (outFile.exists())
                    {
                        outFile.delete();
                    }

                    mediaRecorder=new MediaRecorder();
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    mediaRecorder.setOutputFile(OUTPUT_FILE);
                    mediaRecorder.prepare();
                    mediaRecorder.start();*/

                    record_song.run();

                }

                private void stopRecording()
                {
                   /* if (mediaRecorder !=null)
                    {
                        mediaRecorder.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }*/
                    record_song.close();
                }
            });

            return typingDialogView;
        }
    }

Thanks for any help !

Jéwôm'
  • 3,753
  • 5
  • 40
  • 73

1 Answers1

0

Create a new Java Class(right click on directory -> new -> Java class) with the same name in your project, then paste this code in it.
You now just need to import this class in your code and use it!
For further information see here

magicleon94
  • 4,887
  • 2
  • 24
  • 53
  • Thanks for you help but if I add this class directly on main activity, he do not works ? – programmation1994 Jun 21 '17 at 09:00
  • You can define this class as an inner class in `MainActivity`, just copy what code inside your `MainActivity` class, then use it. Note that `private` means it can be used only within your `MainActivity`. If that's what you like/need, you can do it – magicleon94 Jun 21 '17 at 09:02
  • like any other Java class... `Audio myAudioInstance = new Audio();` – magicleon94 Jun 21 '17 at 09:06
  • i tried,but get always the same error : cannot be referenced by a static context – programmation1994 Jun 21 '17 at 09:11
  • paste the whole `MainActivity` class in your question then, please – magicleon94 Jun 21 '17 at 09:12
  • why is `TypingDialogFragment`defined as `static`? The problem lies here. Remove the `static` identifier and it should work. I don't know why that class should be `static`, and if can not be. If you made that `static` for a reason, you should find another way. The problem is that, from a `static` context (the class you're calling it from is `static`), you cannot reference anything that's not `static`. So, remove that `static` if that does not destroy your purposes ( I don't think it should). – magicleon94 Jun 21 '17 at 09:24
  • I can't remove static, so I have no solution to call "Audio" class ? – programmation1994 Jun 21 '17 at 09:28
  • you can declare `Audio` as a `static` class, but to be honest, I don't know if that is a bad idea or not, I've never done that. – magicleon94 Jun 21 '17 at 09:31
  • or i can just declare my Audio class as static ? – programmation1994 Jun 21 '17 at 09:31
  • Let me know, I'm curious now! – magicleon94 Jun 21 '17 at 09:31
  • If i want to test, i need to use method ? so 'myAudioInstance.run();' // record and stream song ? and 'myAudioInstance.close();' // stop record and stream ? – programmation1994 Jun 21 '17 at 09:39
  • seems to me that just instantiating the class will run the thread, so you just need do close it – magicleon94 Jun 21 '17 at 09:41
  • No problem! Just mark this answer as solution, so your question will appear as solved ;) happy coding! – magicleon94 Jun 21 '17 at 09:45