- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to play sound using Applet in Java?
Problem Description
How to play sound using Applet?
Solution
Following example demonstrates how to play a sound using an applet image using getAudioClip(), play() & stop() methods of AudioClip() class.
import java.applet.*; import java.awt.*; import java.awt.event.*; public class PlaySoundApplet extends Applet implements ActionListener { Button play,stop; AudioClip audioClip; public void init() { play = new Button(" Play in Loop "); add(play); play.addActionListener(this); stop = new Button(" Stop "); add(stop); stop.addActionListener(this); audioClip = getAudioClip(getCodeBase(), "Sound.wav"); } public void actionPerformed(ActionEvent ae) { Button source = (Button)ae.getSource(); if (source.getLabel() == " Play in Loop ") { audioClip.play(); } else if(source.getLabel() == " Stop "){ audioClip.stop(); } } }
Result
The above code sample will produce the following result in a java enabled web browser.
View in Browser.
java_applets.htm
Advertisements