Solved

Playing Sounds

Posted on 2000-04-23
8
291 Views
Last Modified: 2008-03-17
I'm planning out a java program that I would like to run as an applet and as an application.

I would like it to play sounds.

I have some questions going in.

I would like to use java 1.1 so a larger number of people will get the applet.

Can I play .wav files with java 1.1?  If not what file types can I use and how would I convert .wav files to that type?

Could I play the sounds if I put a main() in the applet and run it as an app?

Steve
0
Comment
Question by:Steve34
  • 5
  • 3
8 Comments
 
LVL 7

Accepted Solution

by:
Sasha_Mapa earned 50 total points
ID: 2742430
>>Can I play .wav files with java 1.1?
You most certainly can.
>>Could I play the sounds if I put a main() in the applet and run it as an app?
I understand what you mean here, but don't say that, it's incorrect. Say "Would it work if I did it from an Application?" - Yes, it will work.

Ok, here's how you do it from an applet:

AudioClip clip = getAudioClip(getCodeBase(),"music.wav");
clip.play();

or just
play(getCodeBase(),"music.wav");

just make sure there's a music.wav file in the directory you are running your applet from.

To do that from an application, you just have to use a different method (which you can also use for an applet btw, but it's less convenient) to get the clip.

AudioClip clip = null;
try{
  clip = Applet.newAudioClip(new File("music.wav")).toURL());
} catch (MalformedURLException e){
      e.printStackTrace();
   }
// and now play it just the same way:
clip.play();


you can also invoke clip.stop() to stop it when its playing and clip.loop() to have it play again when it finishes infinitely until you invoke clip.stop()...

If you have more questions on the subject please ask...
0
 

Author Comment

by:Steve34
ID: 2759583
Thanks for the examples!
0
 

Author Comment

by:Steve34
ID: 2760923
Sasha;

I just tried your code.

With the applet version the sound did not play from the *.wav file I used.  My java console gave me the error message "invalid file type".

Your code worked when I substituted a *.au file in.

The code for playing sounds in applications didn't work at all.

Is there a way around any of this or an easy way to convert *.wav files to *.au files?

Thanks in advance

Steve
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

Author Comment

by:Steve34
ID: 2760926
Sasha;

I just tried your code.

With the applet version the sound did not play from the *.wav file I used.  My java console gave me the error message "invalid file type".

Your code worked when I substituted a *.au file in.

The code for playing sounds in applications didn't work at all.

Is there a way around any of this or an easy way to convert *.wav files to *.au files?


I am using Netscape 4.75 on a Windows98 box

Thanks in advance

Steve
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
ID: 2760960
Hmm, actually, I have a working application that I've developed that plays wav files. I conclude from this that this was added in JDK 1.2. You have several ways out of this: You can install the Java plugin on your computer which will enable you running applets in JDK 1.2. Download it from http://java.sun.com/products/plugin/index.html. You could find a au to wav converter which is probably easier, but unfortunately I can't help you with it, I don't know such a converter... Try searching the web with a search engine for "wav au converter"... I'm sure it will produce positive results...
0
 

Author Comment

by:Steve34
ID: 2763613
Okay, I gave up on apps/sounds with java 1.1.

I tried your code with Java2 and I still got nothing.  I am a win98 box with the jdk1.2 and jre 1.2.

I downloaded Sun's sound app example and it works ( but is complex and confusing ).

Here is my/your code ( how I implemented it ).  any help would be appreciated.

( all files are in the same directiory )

Thanks in advance

Steve



import java.applet.*;
import javax.swing.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class SoundExp
{
    public static void main(String[] args )
    {
        AudioClip clip = null;

        try
        {
            clip = Applet.newAudioClip(   new File("gong.wav").toURL()   );
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        // and now play it just the same way:
        clip.play();
                     

    }// end function main()


}// end class SoundExp
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
ID: 2763709
I can't explain it to you very well because I don't completely understand it myself but this has to do with threads. When you are running main, a new non daemon Thread is started and main is called from it. When you call clip.play() from main, it opens another daemon thread and plays the clip in it, the method play() returns immediately. The condition when a Java program dies is when all the non daemon threads have died, so when play() returns, the program exits killing the newly opened daemon thread that is supposed to play the clip. When you do something related to the AWT, like opening a window, another non daemon thread is started, the AWTEventDispatcher, which is responsible to call all of the event listeners whenever an even occurs over a component, as long as that thread is alive, the program will not end. Ever wondered why the following doesn't exit the program at once?

public class MyApp{

  public static void main(String [] args){
    new Frame().show();
  }

}

Exactly for the reason I explained - when you show the Frame, the AWTEventDispatcher is run and  the application will not end until it exits.
Here is an example that does work:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;



public class MyApp extends WindowAdapter implements ActionListener{

  static AudioClip clip;
 
  public static void main(String[] args ){
    Frame f = new Frame();
    f.reshape(50,50,500,500);
    f.addWindowListener(new MyApp());
    f.setLayout(null);
    f.show();
    Button b = new Button("Click me");
    b.addActionListener(new MyApp());
    b.reshape(50,50,60,20);
    f.add(b);
   
    try{
      clip = Applet.newAudioClip(   (new File("Gong.wav")).toURL()   );
    } catch (MalformedURLException e){
        e.printStackTrace();
      }
    // and now play it just the same way:
  }// end function main()

  public void windowClosing(WindowEvent evt){
    evt.getWindow().dispose();
    System.exit(0);
  }

  public void actionPerformed(ActionEvent evt){
    if (clip == null)
      System.out.println("clip is null");
    else{
      System.out.println("playing clip");
      clip.play();
    }
     
  }

}

Good luck, Sasha.
0
 

Author Comment

by:Steve34
ID: 2764506
Wow, it does work.  Thanks!

The only difference is that the sound playing code is embedded in a frame obj.   Interesting!

There are some hard core SUN types on the JDC forums.

I think I will bring up your points there.   I might learn something.

This is the second time since I have been programming Java that the opaque event handling threads have become unopaque in relation to my programs ( only when I've tried interesting things ).

The authors should really start talking about these things more.

Thanks again

Steve
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
difference of if loops 23 49
tomcat not starting 6 45
Custom Java Application connects to database: Which one of the 20? 4 27
use lov values 2 49
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now