2014-12-28 2 views
0

패키지 내의 폴더에 포함 된 .wav 사운드 그룹이 있습니다. 다음 코드에서 버튼을 누를 때마다 항상 동일한 .wav 사운드가 재생됩니다. 폴더에서 읽고 임의의 버튼을 누를 때마다 다른 사운드를 재생하는 임의 기능을 추가하는 방법. 그것이 작동하는 경우랜덤 .wav 사운드를 재생하는 방법?

   public void actionPerformed(ActionEvent e){ 
       if (e.getSource() == Button) 
        play("/nameofthefolder/nameofsound.wav"); 

        }  
+1

배열의 모든 파일 이름을 가져 와서 math.random * array.size를 사용하여 반복적으로 노래의 경로를 선택하십시오. 이 파일을 보면 폴더에있는 모든 파일 이름을 가져올 수 있습니다 (http : // stackoverflow.com/questions/5694385/getting-the-filenames-of-all-files-in-a-folder) –

답변

1
List<String> results = new ArrayList<String>(); 


File[] files = new File("/path/to/the/directory").listFiles(); 
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) { 
    if (file.isFile()) { 
    results.add(file.getName()); 
    } 
} 

public void actionPerformed(ActionEvent e){ 
    String sound=results.get((int) (Math.random()*result.size())); 
    play(sound); 
} 

것은 말해.

+0

다른 방법이 있습니까? –

+0

다른 방법으로 무엇이 필요합니까? 단 하나의 이벤트로 계속해서 플레이하고 싶습니까? @an_barce –

관련 문제