Results 1 to 16 of 16
Like Tree1Likes
  • 1 Post By luppiex

Thread: Need help, in confusion.

  1. #1
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Need help, in confusion.

    Hi, I've got a school project on hand which my teacher asked me to do.
    The problem is while at it I was confused by the fact that whether JRE libraries can be used in Android application or not.
    The project I was asked to do is an Hearing Aid app.
    My Java source code:
    Java Code:
    import java.io.*;
    
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.TargetDataLine;
    
    public class MainActivity  {
    	private IncomingSoundListener isl = new IncomingSoundListener();
        private OutgoingSoundListener osl = new OutgoingSoundListener();
        private boolean inVoice = true;
        private boolean outVoice = false;
        AudioFormat format = getAudioFormat();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        private AudioFormat getAudioFormat() {
        	float sampleRate = 20000.0F;
            int sampleSizeBits = 16;
            int channels = 1;
            boolean signed = true;
            boolean bigEndian = false;
            //AudioFormat.Encoding.ULAW
            return new AudioFormat(sampleRate, sampleSizeBits, channels, signed, bigEndian);
    	}
        public MainActivity(){
        	new Thread(isl).start();
        	new Thread(osl).start();
        	outVoice = true;
        }
    
    	
    	class IncomingSoundListener implements Runnable {
    	    @Override
    	    public void run() {
    	        try {
    	            DataLine.Info speakerInfo = new DataLine.Info(SourceDataLine.class, format);
    	            SourceDataLine speaker = (SourceDataLine) AudioSystem.getLine(speakerInfo);
    	            speaker.open(format);
    	            speaker.start();
    	            while(inVoice) { 
    	                byte[] data = baos.toByteArray();
    	                baos.reset();
    	                ByteArrayInputStream bais = new ByteArrayInputStream(data);
    	                AudioInputStream ais = new AudioInputStream(bais,format,data.length);
    	                int numBytesRead = 0;
    	                if ((numBytesRead = ais.read(data)) != -1) speaker.write(data, 0, numBytesRead);
    	                ais.close();
    	                bais.close();
    	            }
    	            speaker.drain();
    	            speaker.close();
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	        }
    	    }
    	}
    
    	class OutgoingSoundListener implements Runnable {
    	    @Override
    	    public void run() {
    	        try {
    	            DataLine.Info micInfo = new DataLine.Info(TargetDataLine.class, format);
    	            TargetDataLine mic = (TargetDataLine) AudioSystem.getLine(micInfo);
    	            mic.open(format);
    	            byte tmpBuff[] = new byte[mic.getBufferSize()/5];
    	            mic.start();
    	            while(outVoice) {
    	                int count = mic.read(tmpBuff,0,tmpBuff.length);
    	                if (count > 0) baos.write(tmpBuff, 0, count);
    	            }
    	            mic.drain();
    	            mic.close();
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	        }
    	    }
    
    	}
    	public static void main(String[] args) throws IOException {
    	    new MainActivity();   
    	}
    }
    This source code allows me to hear through my headset by capturing sound through the microphone.
    This is what I've done so far, but I have no idea on how I can make it into a Android application project.
    If it is impossible to do that please do point it out to me, so I can maybe get on the right track.
    Thanks.
    Last edited by JosAH; 10-30-2013 at 09:53 AM. Reason: added [code] ... [/code] tags

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: Need help, in confusion.

    The sound api is not part of Android, sadly.
    And you can't just copy the jar file(s) in and expect it to work, either.
    Having had to faff about with MIDI generation and playing on Android it's rather annoying.

    Did some digging around and found this on stack overflow. It covers streaming from the mic to the speaker. It might do what you need?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    Thank you for the speedy reply, this might be just what I needed!

  4. #4
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    Hi, is it possible to control the volume coming in from the mic through using the seekbar? I've seen some examples on seekbar, but it all just controls the volume of the system itself.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: Need help, in confusion.

    No idea I'm afraid.
    It doesn't make sense to control it from the Mic end.
    I would expect you control the volume of the speaker, surely?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    Ahh, yes that. Sorry I have no idea how to phrase my questions properly. Anyway, when I press the toggle button I can hear sounds from my headset. So, I want to know what do I have to write in the else{ part to stop that? And when the button is being toggled, I can't seem to move the seekbar.
    Code:
    Java Code:
    		final ToggleButton tb = (ToggleButton) findViewById(R.id.tb);
    		        tb.setOnClickListener(new View.OnClickListener (){
    			
    			public void onClick(View view) {
    			// TODO Auto-generated method stub
    				boolean on = ((ToggleButton) view).isChecked();
    				if (on){
    					 boolean is = true;
    				     android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
    				     int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    				     AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);
    				     AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);
    				     atrack.setPlaybackRate(11025);
    				     byte[] buffer = new byte[buffersize];
    				     arec.startRecording();
    				     atrack.play();
    				     while(is){
    				     arec.read(buffer, 0, buffersize);
    				     atrack.write(buffer, 0, buffer.length);
    				     }
    				           }else{
    
    				           }
    				           }});
    					
    		}
    Last edited by luppiex; 11-01-2013 at 10:15 AM.

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: Need help, in confusion.

    When posting code please wrap it in [ code ] tags [ /code ].

    As for your problem, you need to keep hold of that AudioTrack as a class member, so you can access it again when the user wants to stop the sound.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    Thanks for the pointer and noted!
    gimbal2 likes this.

  9. #9
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    Why is it when I extract the portion of AudioTrack code to insert it in another class, there will be an error on AudioTrack.MODE_STREAM?
    Can I please have an example which can briefly explain how it should work? And how keep it in hold in a class.
    Last edited by luppiex; 11-03-2013 at 09:09 AM.

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: Need help, in confusion.

    Without seeing the relevant code and the full error you are getting that is an impossible to answer question.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    Hi, I am having trouble opening my app. I can't seem to locate the problem too.
    https://www.dropbox.com/s/a78gu8fhxd...0AudioTest.zip
    Is it fine if someone could take a look and instruct me on the error I'm making?

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: Need help, in confusion.

    Find the stack trace (if it's not opening, there'll be an error somewhere) and then post the relevant code, highlighting where that error is thrown.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    Hi, apparently there is a whole chunk of error in my log.
    11-08 03:20:58.265: E/AndroidRuntime(306): FATAL EXCEPTION: main
    11-08 03:20:58.265: E/AndroidRuntime(306): java.lang.NoClassDefFoundError: android.media.audiofx.Equalizer
    11-08 03:20:58.265: E/AndroidRuntime(306): at com.example.audiotest.MainActivity.onCreate(MainAc tivity.java:86)
    11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.Instrumentation.callActivityOnCreate(I nstrumentation.java:1047)
    11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:2627)
    11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread.handleLaunchActivity(Ac tivityThread.java:2679)
    11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread.access$2300(ActivityThr ead.java:125)
    11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread$H.handleMessage(Activit yThread.java:2033)
    11-08 03:20:58.265: E/AndroidRuntime(306): at android.os.Handler.dispatchMessage(Handler.java:99 )
    11-08 03:20:58.265: E/AndroidRuntime(306): at android.os.Looper.loop(Looper.java:123)
    11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread.main(ActivityThread.jav a:4627)
    11-08 03:20:58.265: E/AndroidRuntime(306): at java.lang.reflect.Method.invokeNative(Native Method)
    11-08 03:20:58.265: E/AndroidRuntime(306): at java.lang.reflect.Method.invoke(Method.java:521)
    11-08 03:20:58.265: E/AndroidRuntime(306): at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.run(ZygoteInit.java:868)
    11-08 03:20:58.265: E/AndroidRuntime(306): at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:626)
    11-08 03:20:58.265: E/AndroidRuntime(306): at dalvik.system.NativeStart.main(Native Method)
    11-08 03:20:58.285: E/AudioThread(306): Thread Loop Exception: java.lang.IllegalArgumentException: Invalid audio buffer size.


    This happened when i tried to implement equalizer into my previous code. Due to being inexperienced, this had to happen. Please be patient and guide me through this.
    I cant understand the second line of error.
    But for the third line,
    Java Code:
    protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		//Audio, mic to speaker
    		setVolumeControlStream(AudioManager.STREAM_MUSIC);
            initControls();
            mAudioThread = new AudioThread();
            mAudioThread.start();
            
            //end
            
            //Equalizer
            enabled = (CheckBox)findViewById(R.id.enabled);
            enabled.setOnCheckedChangeListener (this);
    
            flat = (Button)findViewById(R.id.flat);
            flat.setOnClickListener(this);
    
            bass_boost = (SeekBar)findViewById(R.id.bass_boost);
            bass_boost.setOnSeekBarChangeListener(this);
            bass_boost_label = (TextView) findViewById (R.id.bass_boost_label);
    
            sliders[0] = (SeekBar)findViewById(R.id.slider_1);
            slider_labels[0] = (TextView)findViewById(R.id.slider_label_1);
            //more sliders till slider[4]
            
            mEqualizer = new Equalizer(0, mAudioTrack.getAudioSessionId());//<-----------This line would be the error for 3rd error
            mEqualizer.setEnabled(true);
            
            eq = new Equalizer (0, 0);
            if (eq != null)
              {
              eq.setEnabled (true);
              int num_bands = eq.getNumberOfBands();
              num_sliders = num_bands;
              short r[] = eq.getBandLevelRange();
              min_level = r[0];
              max_level = r[1];
              for (int i = 0; i < num_sliders && i < MAX_SLIDERS; i++)
                {
                int[] freq_range = eq.getBandFreqRange((short)i);
                sliders[i].setOnSeekBarChangeListener(this);
                slider_labels[i].setText (formatBandLabel (freq_range));
                }
              }
    .
    .
    .

    My AudioThread class:
    Java Code:
    public class AudioThread extends Thread {
    
        // Handler message constants
        public static final int PLAY = 0;
        public static final int STOP = 1;
    
        // Class variables
        private boolean mRunning = false;
        private boolean mPlayAudio = false;
    
        
    
        private static class AudioThreadHandler extends Handler {
            private final WeakReference<AudioThread> mThread;
    
            public AudioThreadHandler(AudioThread thread) {
                mThread = new WeakReference<AudioThread>(thread);
            }
    
            @Override
            public  void handleMessage(Message msg) {
                AudioThread thread = mThread.get();
                if (thread != null) {
                    switch(msg.what) {
                    case PLAY:
                        thread.mPlayAudio = true;
                        break;
                    case STOP:
                        thread.mPlayAudio = false;
                        break;
                    }
                }
            }
        };
        static final int bufferSize = 320000;
    	final short[] buffer = new short[bufferSize];
    	short[] readBuffer = new short[bufferSize];
        private final AudioThreadHandler mAudioThreadHandler = new AudioThreadHandler(this);
        
    
        @Override
        public void run() {
            try {
            	int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
                AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);
                AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);
                atrack.setPlaybackRate(11025);
                byte[] buffer = new byte[buffersize];
                arec.startRecording();
                atrack.play();
                mRunning = true;
                while(mRunning) { 
                    if (mPlayAudio) {
                    arec.read(buffer, 0, buffersize);
    				atrack.write(buffer, 0, buffer.length);
                     }else {
    				    }
                    }
                
            } catch (Exception e) {
                Log.e("AudioThread", "Thread Loop Exception: " + e);
            }
        }
    
        public void close() {
            mRunning = false;
        }
    
        public Handler getHandler() {
            return mAudioThreadHandler;
        }
    }
    Last edited by luppiex; 11-08-2013 at 04:43 AM.

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: Need help, in confusion.

    Where are you running this?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  15. #15
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    Sorry for not being active for all this while. I've solved the error above.
    Is there any known way to increase gain of the mic through programming? The sound sounded soft with my device volume at maximum.

  16. #16
    luppiex is offline Member
    Join Date
    Oct 2013
    Posts
    15
    Rep Power
    0

    Default Re: Need help, in confusion.

    There are apps out there that lets you play music at your device volume, but having the capability to further increase the volume with another slider.
    Can I have some examples on controls like this?

Similar Threads

  1. examination confusion
    By rohitj in forum OCMJD
    Replies: 0
    Last Post: 12-24-2011, 02:03 PM
  2. Confusion here @@' Help!
    By pleasurelyours in forum New To Java
    Replies: 7
    Last Post: 06-09-2010, 03:42 PM
  3. Boolean confusion
    By KM88 in forum New To Java
    Replies: 13
    Last Post: 11-02-2009, 12:44 PM
  4. Tic Tac Toe confusion
    By jigglywiggly in forum New To Java
    Replies: 15
    Last Post: 04-12-2009, 01:47 AM
  5. bracket confusion...?
    By gallimaufry in forum New To Java
    Replies: 4
    Last Post: 10-28-2008, 11:17 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •