2016-10-03 82 views
0

我的目標是播放短語「This is a test」的雙重音(雙),它是一個WAV音頻文件。到目前爲止,我成功地生成了一個隨機的短語序列,例如「Test is this a」,但我需要使它只能成對發言,所以「This is」...「是...」每個單詞之間暫停100米,每對之間暫停400毫秒。這是我迄今爲止...在Sound Arrays中隨機播放單詞

public void playDoublets(int numDoublets) throws InterruptedException { 
    ArrayList<Sound> list = new ArrayList(); 
    for (int i =0; i < numWords; i++){ 
     list.add(new Sound(myWordArray[i])); 
    } 
    Collections.shuffle(list); 
    for (int i = 0; i < numWords; i++){ 
     list.get(i).blockingPlay(); 
     Thread.sleep(400); 
    } 
} 

numDoublets是程序有多少雙劇本,但我不知道我會在代碼中實現它上面。所有這些代碼到目前爲止只是打印出所有4個單詞,但不是成對的。

回答

0

您應該在您想播放的聲音列表中明確表示暫停。使用一個界面來統一處理正常的聲音和暫停。

import java.util.*; 

public class DoubletPlayer { 
    private static final int PAUSE_BETWEEN_WORDS = 100; 
    private static final int PAUSE_BETWEEN_DOUBLETS = 400; 

    public static void main(String... args) { 
     DoubletPlayer player = new DoubletPlayer(); 
     player.playDoublets(2); 
    } 

    interface Playable { 
     void play(); 
    } 

    class Sound implements Playable { 
     private String word; 

     public Sound(String word) { 
      this.word = word; 
     } 

     @Override 
     public void play() { 
      System.out.println("sound played: " + word); 
     } 
    } 

    class Pause implements Playable { 
     private int millis; 

     public Pause(int millis) { 
      this.millis = millis; 
     } 

     @Override 
     public void play() { 
      System.out.println("pause of " + millis + "ms"); 
     } 
    } 

    private List<Sound> sounds = new ArrayList<>(); 
    private int currentSound = 0; 

    public DoubletPlayer() { 
     sounds.add(new Sound("This")); 
     sounds.add(new Sound("is")); 
     sounds.add(new Sound("a")); 
     sounds.add(new Sound("test")); 

     Collections.shuffle(sounds); 
    } 

    public void playDoublets(int numDoublets) { 
     List<Playable> doublets = generateDoublets(numDoublets); 
     playAll(doublets); 
     reset(); 
    } 

    private List<Playable> generateDoublets(int numDoublets) { 
     List<Playable> result = new ArrayList<>(); 
     for (int i = 0; i < numDoublets; i++) { 
      addDoubletTo(result); 
     } 
     return result; 
    } 

    private void addDoubletTo(List<Playable> result) { 
     result.add(getNextSound()); 
     result.add(new Pause(PAUSE_BETWEEN_WORDS)); 
     result.add(getNextSound()); 
     result.add(new Pause(PAUSE_BETWEEN_DOUBLETS)); 
    } 

    private Playable getNextSound() { 
     return sounds.get(currentSound++); 
    } 

    private void playAll(List<Playable> result) { 
     for (Playable playable : result) { 
      playable.play(); 
     } 
    } 

    private void reset() { 
     currentSound = 0; 
    } 
} 
+0

非常棒的解決方案,但在這個任務中,我不允許創建接口,我必須使用他們提供給我的類/方法。如果您需要更多信息,請告訴我, – TheDkmariolink