i would like to add sound in my java calculator when an error occurs(e.g when operation *and / are pressed).please help me with the sound code.

Recommended Answers

All 2 Replies

You can always play a sound from a file like this:

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

public class Sound extends JFrame implements ActionListener {
		AudioClip song;
   public Sound() {
	super("Sounds");
	setSize(200,130);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	
	Container pane = getContentPane();
	FlowLayout flo = new FlowLayout();
	pane.setLayout(flo);
	JButton btn = new JButton("Press");
	pane.add(btn);
	btn.addActionListener(this);
        setContentPane(pane);
	setVisible(true);
   }

   public void actionPerformed(ActionEvent event) {


	
   String source = event.getActionCommand();
		 	
	if (source == "Press") {
		try { 
			URL songURL = new URL("file:  errorSound.wav");                
			song = JApplet.newAudioClip(songURL);
			song.play();
		} catch (MalformedURLException malform) {
				System.out.println(malform.toString());
                 }
	}
        else 
	{
	 }
   }
   
   public static void main(String[] arguments) {
	Sound sn = new Sound();
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.