如何使用java类?安卓工作室

Posted

技术标签:

【中文标题】如何使用java类?安卓工作室【英文标题】:How to use java class ? Android studio 【发布时间】:2017-06-21 08:52:13 【问题描述】:

我找到了一个 java 类来帮助立即记录和流式传输数据:

/*
 * 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;
    


来源:Android: Need to record mic input

我想在我的应用程序中使用这个类,但我不知道它是如何工作的。我想从我的主要活动中同时记录和流式传输数据。

编辑 1:我在这里调用对象:

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;
        
    

感谢您的帮助!

【问题讨论】:

【参考方案1】:

在你的项目中新建一个同名的Java Class(右键目录->新建->Java类),然后把这段代码粘贴进去。 您现在只需在代码中导入此类并使用它! 欲了解更多信息,请参阅here

【讨论】:

感谢您的帮助,但如果我直接在主要活动中添加此类,他不起作用? 你可以在MainActivity中将这个类定义为一个内部类,只需复制你的MainActivity类里面的代码,然后使用它。请注意,private 意味着它只能在您的MainActivity 中使用。如果这是你喜欢/需要的,你可以做到 像任何其他 Java 类...Audio myAudioInstance = new Audio(); 我试过了,但总是出现同样的错误:不能被静态上下文引用 请在您的问题中粘贴整个MainActivity 课程

以上是关于如何使用java类?安卓工作室的主要内容,如果未能解决你的问题,请参考以下文章

如何修复“颤振医生 --android-licenses”java 错误?没有安卓工作室

如何获取本地 Wi-Fi 网络中主机名的 IP?安卓工作室(JAVA)

如何编辑虚拟设备?安卓工作室-Java

如何将每个数据保存在 JSON 文件中?安卓工作室

当我们滑过它时如何使按钮执行? (在安卓工作室)

安卓中java和js如何交互