如何在Java中播放一首歌曲的一部分?

时间:2015-08-13 15:35:11

标签: java audio

我只想播放指定序列开头和结尾的歌曲的一部分。我是java中使用歌曲的新手。我写了下面的代码,但是因为播放了整首歌而出了点问题。我应该修改什么?

public class Song implements LineListener {
     
             
    	/**
         * this flag indicates whether the playback completes or not.
         */
        boolean playCompleted;
         
        /**
         * Play a given audio file.
         * @param audioFilePath Path of the audio file.
         */
     
    
    void playFrame(String songName) {
        
    	 File audioFile = new File(songName);
         
    	 try {
             AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
  
             AudioFormat format = audioStream.getFormat();
  
             DataLine.Info info = new DataLine.Info(Clip.class, format);
  
             Clip audioClip = (Clip) AudioSystem.getLine(info);
  
             audioClip.addLineListener(this);
  
             audioClip.open(audioStream);
             
             int nrFrames = audioClip.getFrameLength();
             
             audioClip.setLoopPoints(nrFrames/3, nrFrames/3*2);
              
             audioClip.start();
              
             while (!playCompleted) {
                 // wait for the playback completes
                 try {
                     Thread.sleep(1000);
                 } catch (InterruptedException ex) {
                     ex.printStackTrace();
                 }
             }
              
             audioClip.close();
              
         } catch (UnsupportedAudioFileException ex) {
             System.out.println("The specified audio file is not supported.");
             ex.printStackTrace();
         } catch (LineUnavailableException ex) {
             System.out.println("Audio line for playing back is unavailable.");
             ex.printStackTrace();
         } catch (IOException ex) {
             System.out.println("Error playing the audio file.");
             ex.printStackTrace();
         }
}
    @Override
       public void update(LineEvent event) {
    LineEvent.Type type = event.getType();
     
    if (type == LineEvent.Type.START) {
        System.out.println("Playback started.");
        
    } else if (type == LineEvent.Type.STOP) {
        playCompleted = true;
        System.out.println("Playback completed.");
    }

}
     
   
    public static void main(String[] args)  {
        
        String fileName1 = "song1.wav";
		String fileName2 = "song2.wav";
        Song player = new Song();
        player.playFrame(fileName1);
        
        Song player2 = new Song();
        player2.playFrame(fileName2);
    }
 
}

1 个答案:

答案 0 :(得分:0)

你启动循环点,但不要启动'循环':

 int nrFrames = audioClip.getFrameLength()   
 audioClip.setLoopPoints(nrFrames/3, nrFrames/3*2);

并检查剪辑文档:http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/Clip.html#setLoopPoints(int,%20int)

您似乎需要使用.loop(int count)方法,而不是.start()方法。在这种情况下,您只需将计数设置为1即可播放一次。

编辑:刚看到这是我在打字时被其他人评论的,对不起!