[英]How can I play a song preview in iTunes using Applescript and Java?
[英]How can I play a part of a song in Java?
我只想播放指定序列開頭和結尾的歌曲的一部分。 我是在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); } }
您可以啟動循環點,但是不要啟動“循環”:
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)
方法,而不是.loop(int count)
.start()
方法。 在這種情況下,您只需將計數設置為1即可播放一次。
編輯:剛看到這是別人在我輸入時作為評論,對不起!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.