Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7613913
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T02:16:08+00:00 2026-05-31T02:16:08+00:00

I’m building an application with background music. I’ve written a class to play the

  • 0

I’m building an application with background music.
I’ve written a class to play the music and when I run it it will start playing.
I’ve also written a JFrame view class.

Now I want that when I open my JFrame the music from the other class will play.

How can I do this?

Code from my view class:

package View;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

import javax.swing.JPanel;

import music.PlaySound;

public class Home extends JFrame {

    private JLabel label, label1, label2;
    private JPanel panel;
    private JButton logo;
    private Container window = getContentPane();

    public Home (){
        initGUI();
    }

    public void initGUI(){
        setLayout(null);
        setTitle("Ismail");
        setPreferredSize(new Dimension(800,600));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        label = new JLabel("AFCA");     
        label.setBounds(0, 0, 266, 800);
        label.setBackground(Color.WHITE);
        label.setOpaque(true);
        window.add(label);

        label1 = new JLabel("AFCA1");
        label1.setBounds(267, 0, 266, 800);
        label1.setBackground(Color.RED);
        label1.setOpaque(true);
        window.add(label1);

        label2 = new JLabel("AFCA2");
        label2.setBounds(533, 0, 266, 800);
        label2.setBackground(Color.WHITE);
        label2.setOpaque(true);
        window.add(label2);

        logo = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
        logo.setBorderPainted(false);
        logo.setBounds(40, 100, 188, 188);
        label1.add(logo);

        pack();
    }

}

Code from my sound class:

package music;

import java.io.*;
import javax.sound.sampled.*;

public class PlaySound
{
    public static void main(String[] args)
    {
        sound = new File("../Ajax/src/sound/Sound.wav"); // Write you own file location here and be aware that it needs to be an .wav file

        new Thread(play).start();
    }

    static File sound;
    static boolean muted = false; // This should explain itself
    static float volume = 100.0f; // This is the volume that goes from 0 to 100
    static float pan = 0.0f; // The balance between the speakers 0 is both sides and it goes from -1 to 1

    static double seconds = 0.0d; // The amount of seconds to wait before the sound starts playing

    static boolean looped_forever = false; // It will keep looping forever if this is true

    static int loop_times = 0; // Set the amount of extra times you want the sound to loop (you don't need to have looped_forever set to true)
    static int loops_done = 0; // When the program is running this is counting the times the sound has looped so it knows when to stop

    final static Runnable play = new Runnable() // This Thread/Runnabe is for playing the sound
    {
        public void run()
        {
            try
            {
                // Check if the audio file is a .wav file
                if (sound.getName().toLowerCase().contains(".wav"))
                {
                    AudioInputStream stream = AudioSystem.getAudioInputStream(sound);

                    AudioFormat format = stream.getFormat();

                    if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)
                    {
                        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                                format.getSampleRate(),
                                format.getSampleSizeInBits() * 2,
                                format.getChannels(),
                                format.getFrameSize() * 2,
                                format.getFrameRate(),
                                true);

                        stream = AudioSystem.getAudioInputStream(format, stream);
                    }

                    SourceDataLine.Info info = new DataLine.Info(
                            SourceDataLine.class,
                            stream.getFormat(),
                            (int) (stream.getFrameLength() * format.getFrameSize()));

                    SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
                    line.open(stream.getFormat());
                    line.start();

                    // Set Volume
                    FloatControl volume_control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
                    volume_control.setValue((float) (Math.log(volume / 100.0f) / Math.log(10.0f) * 20.0f));

                    // Mute
                    BooleanControl mute_control = (BooleanControl) line.getControl(BooleanControl.Type.MUTE);
                    mute_control.setValue(muted);

                    FloatControl pan_control = (FloatControl) line.getControl(FloatControl.Type.PAN);
                    pan_control.setValue(pan);

                    long last_update = System.currentTimeMillis();
                    double since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;

                    // Wait the amount of seconds set before continuing
                    while (since_last_update < seconds)
                    {
                        since_last_update = (System.currentTimeMillis() - last_update) / 1000.0d;
                    }

                    System.out.println("Playing!");

                    int num_read = 0;
                    byte[] buf = new byte[line.getBufferSize()];

                    while ((num_read = stream.read(buf, 0, buf.length)) >= 0)
                    {
                        int offset = 0;

                        while (offset < num_read)
                        {
                            offset += line.write(buf, offset, num_read - offset);
                        }
                    }

                    line.drain();
                    line.stop();

                    if (looped_forever)
                    {
                        new Thread(play).start();
                    }
                    else if (loops_done < loop_times)
                    {
                        loops_done++;
                        new Thread(play).start();
                    }
                }
            }
            catch (Exception ex) { ex.printStackTrace(); }
        }
    };
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T02:16:09+00:00Added an answer on May 31, 2026 at 2:16 am

    It sounds like you need to add a WindowListener to your JFrame. Something like this:

    public Home() {
        initGUI();
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                PlaySound.sound = new File("../Ajax/src/sound/Sound.wav");
                soundThread = new Thread(PlaySound.play).start();
            }
            //If you want the sound to stop you can just add another override, but you need to keep track of the sound thread
            @Override
            public void windowClosing(WindowEvent e) {
                soundThread.interrupt();
            }
        });
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
Specifically, suppose I start with the string string =hello \'i am \' me And
I want use html5's new tag to play a wav file (currently only supported
I am doing a simple coin flipping experiment for class that involves flipping a
I would like to run a str_replace or preg_replace which looks for certain words
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
I need a function that will clean a strings' special characters. I do NOT

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.