I havent done java in a while and not sure what to do with the void methods please can someone help me out thanks whole thing is in a zip file as well done in bluej as there is a long list of code here.

/**
 * class Player
 * 
 * @author King000000
 * @version 1.0
 */
public class Player
{
    private PlayList playList;

    /**
     * Constructor ...
     */
    public Player()
    {
        playList = new PlayList("audio");
    }

    /**
     * Return the track collection currently loaded in this player.
     */
    public PlayList getPlayList()
    {
        return playList;
    }

    /**
     * 
     */
    public void play()
    {
         get player.play;
    }

    /**
     * 
     */
 //   public void stop()
    {

    }

    /**
     * 
     */
//    public void setTrack(int trackNumber)
    {

    }

    /**
     * 
     */
//    public String getTrackName()
    {

    }

    /**
     * Return information about the currently selected track. The information
     * contains the track name and playing time, in the format
     *    track-name (playing time)
     * Return an empty string if no track is selected.
     */
//    public String getTrackInfo()
    {

    }
}

// gui is below


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

import java.io.*;

/**
 * A simple sound player. To start, create an instance of this class.
 * 
 * The sound player can play sound clips in WAV, AU and AIFF formats
 * with standard sample rates.
 * 
 * @author Michael Kolling and David J Barnes 
 * @version 1.0
 */
public class SoundPlayerGUI extends JFrame
    implements ListSelectionListener
{
    private static final String VERSION = "Version 1.0";

    private JList fileList;
    private JLabel infoLabel;
    private Player player;


    /**
     * Create a SoundPlayer and display its GUI on screen.
     */
    public SoundPlayerGUI()
    {
        super("kentSound");
        player = new Player();
        PlayList tracks = player.getPlayList();
        makeFrame(tracks);
    }

    /**
     * Play the sound file currently selected in the file list. If there is no
     * selection in the list, or if the selected file is not a sound file, 
     * do nothing.
     */
    private void play()
    {
        player.play();
    }

    /**
     * Display information about a selected sound file (name and clip length).
     * @param message The message to display.
     */
    private void showInfo(String message)
    {
        infoLabel.setText(message);
    }

    /**
     * Stop the currently playing sound file (if there is one playing).
     */
    private void stop()
    {
        player.stop();
    }

    /**
     * Quit function: quit the application.
     */
    private void quit()
    {
        System.exit(0);
    }


    /**
     * About function: show the 'about' box.
     */
    private void showAbout()
    {
        String text = "kentSound\n" + VERSION;

// CHALLENGE TASK: REMOVE THE LINE ABOVE, AND UNCOMMENT THE FOLLOWING 4 LINES:
//         String text = "kSound\n" + VERSION + "\n"
//                       + "Total tracks played: " + player.getNumberOfTracksPlayed() + "\n"
//                       + "Total track time: " + player.getTotalPlayedTrackLength() + "\n"
//                       + "Average track time: " + player.averageTrackLength();

        JOptionPane.showMessageDialog(this, 
                    text,
                    "About SoundPlayer", 
                    JOptionPane.INFORMATION_MESSAGE);
    }

    // --- ListSelectionListener interface ---

    /**
     * List selection changed. Called when the user select an entry in the track list.
     */
    public void valueChanged(ListSelectionEvent evt)
    {
        int selected = fileList.getSelectedIndex();
        if(selected != -1) {
            player.setTrack(selected);
        }
        showInfo(player.getTrackInfo());
    }

    // ---- Swing stuff to build the frame and all its components and menus ----

    /**
     * Create the complete application GUI.
     * @param audioFiles The file names to display.
     */
    private void makeFrame(PlayList tracks)
    {
        // the following makes sure that our application exits when
        // the user closes its window
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel contentPane = (JPanel)getContentPane();
        contentPane.setBorder(new EmptyBorder(6, 10, 10, 10));

        makeMenuBar();

        // Specify the layout manager with nice spacing
        contentPane.setLayout(new BorderLayout(8, 8));

        // Create the left side with combobox and scroll list
        JPanel leftPane = new JPanel();
        {
            leftPane.setLayout(new BorderLayout(8, 8));

            // Create the scrolled list for file names
            fileList = new JList(tracks.asStrings());
            fileList.setForeground(new Color(212,212,255));
            fileList.setBackground(new Color(0,85,150));
            fileList.setSelectionBackground(new Color(212,212,255));
            fileList.setSelectionForeground(new Color(0,45,75));
            fileList.addListSelectionListener(this);
            JScrollPane scrollPane = new JScrollPane(fileList);
            scrollPane.setColumnHeaderView(new JLabel("Tracks"));
            leftPane.add(scrollPane, BorderLayout.CENTER);
        }
        contentPane.add(leftPane, BorderLayout.CENTER);

        // Create the center with image, text label, and slider
       JPanel centerPane = new JPanel();
        {
            centerPane.setLayout(new BorderLayout(8, 8));

            JLabel image = new JLabel(new ImageIcon("title.jpg"));
            centerPane.add(image, BorderLayout.NORTH);
            centerPane.setBackground(Color.WHITE);

            infoLabel = new JLabel("  ");
            infoLabel.setHorizontalAlignment(SwingConstants.CENTER);
            infoLabel.setForeground(new Color(0,85,150));
            centerPane.add(infoLabel, BorderLayout.CENTER);

            centerPane.add(new JLabel("  "), BorderLayout.SOUTH);
        }
        contentPane.add(centerPane, BorderLayout.EAST);

        // Create the toolbar with the buttons
        JPanel toolbar = new JPanel();
        {
            toolbar.setLayout(new GridLayout(1, 0));

            JButton button = new JButton("Play");
            button.addActionListener(new ActionListener() {
                                   public void actionPerformed(ActionEvent e) { play(); }
                               });
            toolbar.add(button);

            button = new JButton("Stop");
            button.addActionListener(new ActionListener() {
                                   public void actionPerformed(ActionEvent e) { stop(); }
                               });
            toolbar.add(button);
        }

        contentPane.add(toolbar, BorderLayout.NORTH);

        // building is done - arrange the components      
        pack();

        // place this frame at the center of the screen and show
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(d.width/2 - getWidth()/2, d.height/2 - getHeight()/2);
        setVisible(true);
    }

    /**
     * Create the main frame's menu bar.
     */
    private void makeMenuBar()
    {
        final int SHORTCUT_MASK =
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();

        JMenuBar menubar = new JMenuBar();
        setJMenuBar(menubar);

        JMenu menu;
        JMenuItem item;

        // create the File menu
        menu = new JMenu("File");
        menubar.add(menu);

        item = new JMenuItem("Quit");
            item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
            item.addActionListener(new ActionListener() {
                               public void actionPerformed(ActionEvent e) { quit(); }
                           });
        menu.add(item);

        // create the Help menu
        menu = new JMenu("Help");
        menubar.add(menu);

        item = new JMenuItem("About SoundPlayer...");
            item.addActionListener(new ActionListener() {
                               public void actionPerformed(ActionEvent e) { showAbout(); }
                           });
        menu.add(item);
    }
}


// playlist below

import java.util.List;
import java.util.ArrayList;
import java.io.File;

/**
 * A PlayList is a list of playable audio tracks. On creation, a directory
 * name is specified, and all audio tracks in that directory will be
 * automatically added to the play list. Files in the directory that cannot
 * be decoded are ignored.
 * 
 * @author Michael Kolling
 * @version 2006-10-09
 */
public class PlayList
{
    private List<Track> tracks; 

    /**
     * Constructor for objects of class TrackCollection
     */
    public PlayList(String directoryName)
    {
        tracks = loadTracks(directoryName);
    }

    /**
     * Return a track from this collection.
     */
    public Track getTrack(int trackNumber)
    {
        return tracks.get(trackNumber);
    }

    /**
     * Return the number of tracks in this collection.
     */
    public int numberOfTracks()
    {
        return tracks.size();
    }

    /**
     * Load the file names of all files in the given directory.
     * @param dirName Directory (folder) name.
     * @param suffix File suffix of interest.
     * @return The names of files found.
     */
    private List<Track> loadTracks(String dirName)
    {
        File dir = new File(dirName);
        if(dir.isDirectory()) {
            File[] allFiles = dir.listFiles();
            List<Track> foundTracks = new ArrayList<Track>();

            for(File file : allFiles) {
                //System.out.println("found: " + file);
                Track track = new Track(file);
                if(track.isValid()) {
                    foundTracks.add(track);
                }
            }
            return foundTracks;
        }
        else {
            System.err.println("Error: " + dirName + " must be a directory");
            return null;
        }
    }

    /**
     * Return this playlist as an array of strings with the track names.
     */
    public String[] asStrings()
    {
        String[] names = new String[tracks.size()];
        int i = 0;
        for(Track track : tracks) {
            names[i++] = track.getName();
        }
        return names;
    }
}



// track below


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

/**
 * A sound track. The track can be instantiated with a valid sound file,
 * and the track object can then be used to control the sound.
 * 
 * The track accepts files in WAV, AIFF, and AU formats (although 
 * not all WAV files - it depends on the encoding in the file).
 * 
 * Watch out, once a track has been played, it can only be played again 
 * if it has been stopped first. So the sequence  play-play does not work,
 * not play-stop-play does.
 * 
 * @author mik
 * @version 2008-10-13
 */
public class Track
{
    private Clip soundClip;
    private String name;
    /**
     * Create a track from an audio file.
     */
    public Track(File soundFile)
    {
        soundClip = loadSound(soundFile);
        name = soundFile.getName();
    }

    /**
     * Play this sound track. (The sound will play asynchronously, until 
     * it is stopped or reaches the end.)
     */
    public void play()
    {
        if(soundClip != null) {
            soundClip.start();
        }
    }

    /**
     * Stop this track playing. (This method has no effect if the track is not
     * currently playing.)
     */
    public void stop()
    {
        if(soundClip != null) {
            soundClip.stop();
        }
    }

    /**
     * Reset this track to its start.
     */
    public void rewind()
    {
        if(soundClip != null) {
            soundClip.setFramePosition(0);
        }
    }

    /**
     * Return the name of this track.
     */
    public String getName()
    {
        return name;
    }

    /**
     * Return the duration of this track, in seconds.
     */
    public int getDuration()
    {
        if (soundClip == null) {
            return 0;
        }
        else {
            return (int) soundClip.getMicrosecondLength()/1000000;
        }
    }

    /**
     * Set the playback volume of the current track.
     * 
     * @param vol  Volume level as a percentage (0..100).
     */
    public void setVolume(int vol)
    {
        if(soundClip == null) {
            return;
        }
        if(vol < 0 || vol > 100) {
            vol = 100;
        }

        double val = vol / 100.0;

        try {
            FloatControl volControl =
              (FloatControl) soundClip.getControl(FloatControl.Type.MASTER_GAIN);
            float dB = (float)(Math.log(val == 0.0 ? 0.0001 : val) / Math.log(10.0) * 20.0);
            volControl.setValue(dB);
        } catch (Exception ex) {
            System.err.println("Error: could not set volume");
        }
    }

    /**
     * Return true if this track has successfully loaded and can be played.
     */
    public boolean isValid()
    {
        return soundClip != null;
    }

    /**
     * Load the sound file supplied by the parameter.
     * 
     * @return  The sound clip if successful, null if the file could not be decoded.
     */
    private Clip loadSound(File file) 
    {
        Clip newClip;

        try {
            AudioInputStream stream = AudioSystem.getAudioInputStream(file);
            AudioFormat format = stream.getFormat();

            // we cannot play ALAW/ULAW, so we convert them to PCM
            //
            if ((format.getEncoding() == AudioFormat.Encoding.ULAW) ||
                (format.getEncoding() == AudioFormat.Encoding.ALAW)) 
            {
                AudioFormat tmp = new AudioFormat(
                                          AudioFormat.Encoding.PCM_SIGNED, 
                                          format.getSampleRate(),
                                          format.getSampleSizeInBits() * 2,
                                          format.getChannels(),
                                          format.getFrameSize() * 2,
                                          format.getFrameRate(),
                                          true);
                stream = AudioSystem.getAudioInputStream(tmp, stream);
                format = tmp;
            }
            DataLine.Info info = new DataLine.Info(Clip.class, 
                                           stream.getFormat(),
                                           ((int) stream.getFrameLength() *
                                           format.getFrameSize()));

            newClip = (Clip) AudioSystem.getLine(info);
            newClip.open(stream);
            return newClip;
        } catch (Exception ex) {
            return null;
        }
    }
}

Edited 3 Years Ago by Nick Evan: Fixed formatting

I havent done java in a while and not sure what to do with the void methods please can someone help me out thanks whole thing is in a zip file as well done in bluej as there is a long list of code here. }

you mean you've putted void method's in your code without knowing whether or not you'll use them, and even not knowing what they're supposed to do?

a void method is usually used to perform an action, without expecting a result.

for instance, two kids fighting:

in class Kid, you'd have:

public void getsKicked(String otherKidsName){
  System.out.println("" + this.getName() + " got kicked by + " otherKidsName);
}

and that other kid would love this situation. but, in reality, the other kid would kick back, OO-terms thinking => he would return a result:

public String getsKicked(String otherKidsName){
  System.out.println("" + getName() + " got kicked by " + otherKidsName);
  return otherKidsName + " just got kicked back by " + getName + " really hard".
}

whatever you do within a void method, stays in that method (unless you go and change values of variables you didn't declare in that method.
the other version returns a String. so you could say this:

Kid a = new Kid("Burt");
Kid b = new Kid("Jeff");

b.getsKicked(a.getName());
String answer = b.getsKicked(a.getName());

Hi king000000 and welcome to DaniWeb :)

The play method should either:

Start playing a track if the player is not already playing;
OR
Do nothing if the player is already playing.

The stop method should either:

Stop playing the track if the player is playing;
OR
Do nothing if the player is not playing.

To do both of these methods (play and stop) you will need to maintain the state of the Player. This will involve a simple state machine - draw diagrams before you begin, it will be easier in the long run. You will need to play a Track when the state is playing and the GUI should probably display some way to inform the user that it is playing.

The setTrack method should:

Change the current track to the specified value - need another member variable for this.

These tips should give you something to go on. If you need more help, feel free to repost with another question. :)

Hi I am still stuck can you show me the code needed for the play method then I will have a go at doing the stop method myself and I am really pushed for time need to finish this in 2 hours time, any help would be good thanks

"The play method should either:

Start playing a track if the player is not already playing;
OR
Do nothing if the player is already playing."

well.. I see no

public boolean isRunning(){
 ...
}

in that track list, so what you can do, is keep a local boolean, which you set to true when you start playing a song. so you can do:

private boolean isPlaying = false;
private Track track;

 ...

 public void play(){
    if (!isPlaying){
       this.isPlaying = true;
      track.play();
    }
 }

  public void stop(){
     if ( isPlaying){
         this.isPlaying = false;
        track.stop();
    }
   }

ok thanks for that but i still cant compile the program and would really like to test it can you quicky add the code needed for these methods please:


/**
*
*/
public void setTrack(int trackNumber)
{

}

/**
*
*/
public String getTrackName()
{

}

/**
* Return information about the currently selected track. The information
* contains the track name and playing time, in the format
* track-name (playing time)
* Return an empty string if no track is selected.
*/
public String getTrackInfo()
{

}
}


please look at the zip file in my first post thanks ( kentsound.zip has everything in it)

thanks

just noted i can edit posts rather than making new ones see last post thanks

ok thanks for that but i still cant compile the program and would really like to test it can you quicky add the code needed for these methods please:

you do relise that these getters and setters are the very basic of OO programming, do you?
it's no use trying to write a MediaPlayer, no matter how simple, if you haven't got the hang of those yet. anyway, here you are, and I'm just guessing you've been respecting the naming conventions

public void setTrack(int trackNumber)
{
   this.track = trackNumber;
   // although I must say this.trackNumber = trackNumber sounds more logical, but then
   // it would be setTrackNumber(int trackNumber)
}

public String getTrackName()
{
    return this.trackName;
}

public String getTrackInfo()
{
     return this.trackInfo;
}

ok thanks again can I ask just one last thing still having trouble compiling it can you download the zip file open it and edit and save and re upload it many thanks again

public void setTrack(int trackNumber){ this.track = trackNumber; // although I must say this.trackNumber = trackNumber sounds more logical, but then // it would be setTrackNumber(int trackNumber)}

this gives me incompatable types found int but expected Track

if it doesn't compile, it gives you an exception message. look at why it isn't compiling, in a lot of cases it states specificly what the problem is and on which line of which class it can be found.

if you can't find it, post the error message here

public void setTrack(int trackNumber){ this.track = trackNumber; // although I must say this.trackNumber = trackNumber sounds more logical, but then // it would be setTrackNumber(int trackNumber)}

this gives me incompatable types found int but expected Track

that's because you didn't follow naming conventions.

if you say: setTrack, that means you want to set the variable with the name 'track'
obviously, either your name for your method is wrongly chosen, or the argument you're passing is wrong

ok this zip i uploaded is a school working i am ment to get player.class with all 5 methods working obviously its not straight foward, is there any charce in your looking through what i have done and if you can at least get the thing compiling id be really happy

maybe I'll look at it tonight, but if it is just getting getters and setters to work, it's best for you to get it working on your own.
unless you manage to work with them in a proper way, you'll be failing the hell out of your class

yeah guess so, but if you can havea look at it tonight that would be great

If you tell us what the compiler errors are we will try to give you hints as to how to fix it yourself. That way you will learn more than if we just go ahead and fix it for you (which would be cheating btw). In the end you would only be cheating yourself...

hahahha I am not hijacking? I am doing the same project as the person who had this thread so I thought I would continue it. I see that you helped him with his project.

This article has been dead for over six months. Start a new discussion instead.