Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 24 of 24

Thread: Threading problem? - hopefully in the correct forum this time

  1. #1
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Threading problem? - hopefully in the correct forum this time

    I'm just writing my second Java program (after "Hello World!") to generate tones for a morse code program. I've found some code, but when I try to run it all the tones appear at the same time. How do I make the tones/spaces sequential?

     
    package tones1;
     
    public class Tones1
     
    {
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args)
        {
            int tone = 750;
            long duration = 200;
     
            SynthAudioClip MyDot = new SynthAudioClip(750, duration);
            SynthAudioClip MyDash = new SynthAudioClip(750, 3*duration);
            SynthAudioClip MyCharSpace = new SynthAudioClip(20000, duration);
            SynthAudioClip MyWordSpace = new SynthAudioClip(0, 5*duration);
     
            MyDot.play();
            MyCharSpace.play();
            MyDash.play();
            MyCharSpace.play();
        }
    }
     
    package tones1;
     
    // SynthAudioClip - a synthesized audio clip
     
    import java.applet.AudioClip;
    import java.io.IOException;
    import java.io.InputStream;
    import sun.audio.AudioData;
    import sun.audio.AudioDataStream;
    import sun.audio.AudioPlayer;
    import sun.audio.ContinuousAudioDataStream;
     
    //
    // Copyright (C) 1996 by Jef Poskanzer <jef@mail.acme.com>.  All rights reserved.
    //
    // Redistribution and use in source and binary forms, with or without
    // modification, are permitted provided that the following conditions
    // are met:
    // 1. Redistributions of source code must retain the above copyright
    //    notice, this list of conditions and the following disclaimer.
    // 2. Redistributions in binary form must reproduce the above copyright
    //    notice, this list of conditions and the following disclaimer in the
    //    documentation and/or other materials provided with the distribution.
    //
    // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
    // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    // ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
    // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    // SUCH DAMAGE.
    //
    // Visit the ACME Labs Java page for up-to-date versions of this and other
    // fine Java utilities: [url]http://www.acme.com/java/[/url]
     
    // package Acme;
     
    // import java.io.*;
    // import java.applet.AudioClip;
    // import sun.audio.*;
     
    /// A synthesized audio clip.
    // <P>
    // Generates a synthetic audio tone of a specified frequency and duration.
    // <P>
    // <A HREF="/resources/classes/Acme/SynthAudioClip.java">Fetch the software.</A><BR>
    // <A HREF="/resources/classes/Acme.tar.gz">Fetch the entire Acme package.</A>
     
    public class SynthAudioClip implements AudioClip
        {
        private static final long SAMPLES_PER_SEC = 8000;
     
        AudioData data;
        InputStream stream;
     
        /// Constructor.
        // Generates a single tone.
        // @param hz the frequency of the tone
        // @param millis the duration of the tone, in milliseconds
        // @param amplitude the loudness of the tone, from 0 to 32767
        public SynthAudioClip( int hz, long millis, double amplitude )
    	{
    	int samples = (int) ( millis * SAMPLES_PER_SEC / 1000 );
    	byte[] buf = new byte[samples];
    	for ( int i = 0; i < buf.length; ++i )
    	    buf[i] = toUlaw( (int) (
    		amplitude *
    		Math.sin( 2.0D * Math.PI * i * hz / SAMPLES_PER_SEC ) ) );
    	data = new AudioData( buf );
    	}
     
        /// Constructor.
        // Generates a single tone, with default loudness.
        // @param hz the frequency of the tone
        // @param millis the duration of the tone, in milliseconds
        public SynthAudioClip( int hz, long millis )
    	{
    	this( hz, millis, 16384.0D );
    	}
     
     
        private static final int[] expLut = {
    	0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 
    	4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 
    	5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
    	5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
    	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 
    	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 
    	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 
    	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 
    	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
    	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
    	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
    	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
    	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
    	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
    	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
    	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
    	};
        private static final int CLIP = 32635;
        private static final int BIAS = 0x84;
     
        private static byte toUlaw( int linear )
    	{
    	int sign, exponent, mantissa;
    	byte ulaw;
     
    	// Get the sample into sign-magnitude.
    	if ( linear >= 0 )
    	    sign = 0;
    	else
    	    {
    	    sign = 0x80;
    	    linear = -linear;
    	    }
            if ( linear > CLIP )
    	    linear = CLIP;	// clip the magnitude
     
    	// Convert from 16 bit linear to ulaw.
    	linear = linear + BIAS;
    	exponent = expLut[( linear >> 7 ) & 0xFF];
    	mantissa = ( linear >> ( exponent + 3 ) ) & 0x0F;
    	ulaw = (byte) ( ~ ( sign | ( exponent << 4 ) | mantissa ) );
    	return ulaw;
    	}
     
     
        public synchronized void play()
    	{
    	stop();
    	if ( data != null )
    	    {
    	    stream = new AudioDataStream( data );
    	    AudioPlayer.player.start( stream );
    	    }
    	}
     
        public synchronized void loop()
    	{
    	stop();
    	if ( data != null )
    	    {
    	    stream = new ContinuousAudioDataStream( data );
    	    AudioPlayer.player.start( stream );
    	    }
    	}
     
        public synchronized void stop()
    	{
    	if ( stream != null )
    	    {
    	    AudioPlayer.player.stop( stream );
    	    try
    		{
    		stream.close();
    		}
    	    catch ( IOException iignore ) {}
    	    stream = null;
    	    }
    	}
        }
    Last edited by gm3xvr; July 1st, 2012 at 11:58 AM. Reason: Code indentation


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Please change the code tags. The ending should use / not \
    Edit your post and wrap your code with
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,355
    Thanks
    182
    Thanked 833 Times in 776 Posts
    Blog Entries
    5

    Default Re: Threading problem? - hopefully in the correct forum this time

    Please read the forum rules. It describes how to properly use the code tags, and that double posting is not allowed (as a result, your other post has been deleted)

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Try putting a call to the Thread sleep() method between the calls to play().
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    I tried:

     
            MyDot.play();
            Thread.sleep(duration);

    but I get the error:

    unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
    ----

    Do I have the format correct?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Put that code in a try/catch block
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Hi Norm

    I'm still reading the book, so had to jump forward to that section.

    I tried:

     
            MyDot.play();
            try
            {
                Thread.sleep(duration);
            }
            catch (java.lang.RuntimeException e)
            {
                System.out.println("caught");
            }

    and it printed "caught".

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Put:
    e.printStackTrace();
    in the catch block to see what exception is being thrown.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    I tried:

     
            MyDot.play();
            try
            {
                Thread.sleep(duration);
            }
            catch (java.lang.RuntimeException e)
            {
                e.printStackTrace();
                System.out.println("caught");
            }

    but I didn't get any more output (only "caught")..

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Are you sure you are executing the code that is posted? The stack trace has to print BEFORE "caught" is printed.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Hi Norm.

    I'm using NetBeans and the output I get is:

    run:
    caught
    java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
    at tones1.Tones1.main(Tones1.java:24)
    BUILD SUCCESSFUL (total time: 9 seconds)

    Does e.printStackTrace(); print on the screen?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Sorry, I don't use that IDE and don't know about its error messages. What error do you get when you try to compile the code with the javac command?

    Why does the code catch the RuntimeException?
    Is that what your documentation says the sleep() method throws?
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Yes. The error is associated with the Thread.sleep(duration); line in the code.

    I only got this up and running yesterday, so this is my first attempt at java. I've done a bit of C programming, but the whole java environment is new to me.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Look at the API doc for the sleep() method. It gives the name of the exception.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Hi Norm.

    I'm on kitchen duty tonight, so I'll get back to this in a couple of hours time.

    Thanks for your help so far.

  16. #16
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Hi Norm.

    I've had a look but I can't see anything unusual in the code.

    This routine looked the simplest to implement to give me a variable tone and duration, and it works for single beeps, but unfortunately I don't have the rest of the code to see how it was used. When I try to run it with several beeps, they all seem to occur at the same time on top of one another without any gaps between them. I guess I need a lot more than a few days experience to get this working. Back to the manuals ...

    Thanks for your help.

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    What happens when you call sleep() between the calls to play()?
    If you don't understand my answer, don't ignore it, ask a question.

  18. #18
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Hi Norm.

    If I use the following code:

     
            MyDot.play();
            try
            {
                Thread.sleep(duration);
            }
            catch (java.lang.RuntimeException e)
            {
                e.printStackTrace();
                System.out.println("caught");
            }

    I get the error message:

    "unreported exception java.lang.InterruptedException; must be caught or declared to be thrown" for the Thread.sleep(duration); line of code, and the code won't compile.

    I'm just off to work now, so I'll pick this up again this evening.

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Have you read my earlier posts? eg #12 & #14
    Did you read the API doc for the sleep() method to see what exception it can throw?
    Why are you catching the RuntimeException?
    If you don't understand my answer, don't ignore it, ask a question.

  20. #20
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Hi Norn.

    I am new to java, object oriented programming and threading. My previuos experience was with embedded C where code ran in sequence.

    I have read your previous posts and looked at the API for sleep(). It can throw "InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown." I'm not sure what this means.

    In my code I have:

     
            MyDot.play();
            Thread.sleep(2* duration);

    The Thread.sleep(2* duration); line is underlined with the error:

    "unreported exception java.lang.InterruptedException; must be caught or declared to be thrown"

    and the code does not compile. I don't know what to do to get rid of this compiler error. I was hoping that it was something obviuos that I was doing wrong. Meanwhile I'll go back to working my way through the book.

    Thanks for your help.

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    InterruptedException; must be caught
    You need to wrap the call to the sleep() method in a try/catch block. The catch must be for the exception that sleep() can throw.
    sleep(). It can throw "InterruptedException
    If you don't understand my answer, don't ignore it, ask a question.

  22. #22
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Hi Norm.

    Very many thanks for that hint.

    I have the code running now, generating some morse code. It seems a bit cumbersome to have to put:

     
                    MyDot.play();
                    try
                    {
                        Thread.sleep(duration);
                    }    
                    catch (InterruptedException e)
                    {
                        System.out.println("caught exception");
                    }
                    MyDash.play();
                    try
                    {
                        Thread.sleep(duration);
                    }    
                    catch (InterruptedException e)
                    {
                        System.out.println("caught exception");
                    }

    just to send the letter 'a', but at least it is working.

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,884
    Thanks
    55
    Thanked 2,348 Times in 2,319 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Now you need to do some thinking on how to do all the characters.

    Why are you working on Morse code? I did a project for Morse code about 10 years ago.
    I put one version on a website:
    Morse code sounder
    If you don't understand my answer, don't ignore it, ask a question.

  24. #24
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threading problem? - hopefully in the correct forum this time

    Hii Norm.

    I've got the characters all defined now.

    Mnay years ago I wrote a morse code trainer program in GWBASIC, which sent randon 5 letter groups at a target speed (say 25 wpm), but spaced so that the thinking time between characters was increased to give a current rate (say 15 wpm). This now seems to be called the Farnsworth method, although I had never heard of it when I wrote my program. There are some java programs around that operate like this, but what I did with mine was to gradually decrease the spacing between characters if you typed the code back in correctly, or hold the speed constant and increase the weighting of any characters that you got wrong, so that you either got your morse up to your typing speed or your typing up to your morse speed. Individual characters could be enabled/disabled as required.

    I'll mark this thread as closed now, but you may see me posting again if I have more problems. Unfortunately the programmers at work don't use java, so I have to rely on books, forums and the web.

    Thanks again.

Similar Threads

  1. First time in forum
    By prasanth1216 in forum Member Introductions
    Replies: 0
    Last Post: December 19th, 2010, 01:45 PM
  2. java threading execution time question
    By centenial in forum Threads
    Replies: 4
    Last Post: September 9th, 2010, 12:32 AM
  3. problem in Threading !!!
    By roadies07 in forum Threads
    Replies: 4
    Last Post: July 14th, 2010, 11:21 AM
  4. Problem in Threading , ThreadGroup
    By neo_2010 in forum Threads
    Replies: 1
    Last Post: August 31st, 2009, 12:19 AM