关于Java中的音乐项目的几个问题

时间:2012-03-12 22:13:13

标签: java

我有一些关于我正在研究的学校项目的问题。代码如下。

public class Player
{
private PlayList playList;
private Track track;
private int tracksPlayed;
private int totalTrackTime;
private double averageTrackTime;

/**
 * Constructor ...
 */
public Player()
{
    playList = new PlayList("audio");
    track = playList.getTrack(0);
    this.tracksPlayed = tracksPlayed;
    this.totalTrackTime = totalTrackTime;
    this.averageTrackTime = averageTrackTime;
}

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

/**
 * 
 */
public void play()
{
    track.play();
    tracksPlayed++;
    int trackDuration = track.getDuration();
    totalTrackTime = totalTrackTime + trackDuration;
    averageTrackTime = totalTrackTime / tracksPlayed;
}

/**
 * 
 */
public void stop()
{
    track.stop();
}

/**
 * 
 */
public void setTrack(int trackNumber)
{
    int currentTrack = trackNumber;
    track = playList.getTrack(currentTrack);
}

/**
 * 
 */
public String getTrackName()
{
    String currentTrack = track.getName();
    return currentTrack;
}

/**
 * 
 */
public String getTrackInfo()
{
    String currentTrack = track.getName();
    int trackDuration = track.getDuration();
    return currentTrack + " " + "(" + trackDuration + ")";
}

/**
 * 
 */
public int getNumberOfTracksPlayed()
{
    return tracksPlayed;
}

/**
 * 
 */
public int getTotalPlayedTrackLength()
{
    return totalTrackTime;
}

/**
 * 
 */
public double averageTrackLength()
{
    return averageTrackTime;
}
}


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

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;
}
}
  1. 我明白要调用播放器类中的play方法,我必须初始化一个Track类变量。我还需要使用PlayList getTrack方法对其进行初始化。但是,如何在不定义起始索引变量的情况下初始化它(即我不希望它自动初始化为索引中的特定歌曲,我希望用户必须先选择一首歌曲)?

    < / LI>
  2. 另外,如果在开始播放新歌之前正在播放现有歌曲并且如果再次在同一首歌中再次调用播放方法,则如何编写播放器类中的播放方法以停止现有歌曲?

1 个答案:

答案 0 :(得分:0)

1

  

如何在不定义起始索引变量

的情况下初始化它
public Player (int initTrack){
   ...
   track = playList.getTrack(initTrack);
   ...
}

2。 您应该尝试使用存储当前正在播放的曲目的字段!