0

Yes i do know this have been posted atleast two times before, but i can hardly get anyhelp out of it. So back to my post, trying to figure out what i am doing wrong, and why my class wont compile. So i am not really sure what to do, any help would be appreciated thanks :)
This is a bluej assignment, not asking for you to do my school assignment, i just need a "push" in the right direction :)

Player Class

/**
 * Write a description of class Player here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Player
{
    private PlayList playList;
    private boolean isPlaying =false;
    private Track track;

    /**
     * Constructor ...
     */
    public Player()
    {
        playList = new PlayList("audio");
        track = new Track(); <- Error here

    }

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

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

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

    /**
     * 
     */
    public void setTrack(int trackNumber)
    {
        this.track = trackNumber; <-- error here "incompatible types: int cannot be converted to Track"
    }

    /**
     * 
     */
    public String getTrackName()
    {
        return this.trackName; <-- error here "cannot find sympol"
    }

    /**
     * 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()
    {
        return this.trackInfo; <-- error here "cannot find sympol"
    }
}

Playlist Class

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 Class

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;
        }
    }
}

SoundPlayerGUI Class

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);
    }
}

Edited by tor-arne

3
Contributors
4
Replies
21
Views
1 Week
Discussion Span
Last Post by JamesCherrill
1

To me this looks like code that has a lot of missing methods. Also, it looks a lot like what was in the BlueJ programming book.
https://github.com/drblinken/informatica-examples/tree/master/eclipse/BlueJ/src/chapter11/musicplayer for example. Since it's not homework, you should either get that book so you see how it's done or publish the entire code base.

Well i do have the book, but its an assignment that isnt in the book, since its give by our teacher. All the info we get from out teacher is that we should start with fixing t he methods in the "player" class. I could public the entire code base.

Edited by tor-arne

Votes + Comments
Thanks for the added code. I couldn't find methods before.
1

19: The Track class does not have a constructor with no args.
58: you are trying to assign an int to a Track object - obviously not possible
66,77: you are referring to variables that do not exist in that class

what kind of help are you asking for?

Votes + Comments
No argument here. Assertions indeed fail.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.