我更喜欢使用Java使用以下代码逐一播放多个音频,但是,floder'res'中的所有音频会同时播放。
package com.company;
import java.io.*;
import sun.audio.*;
public class Main {
public static void main(String[] args)
throws Exception
{
String resPath="res/";
File f=new File(resPath);
File[] result=f.listFiles();
String[] filePath=new String[result.length];
for(int i=0;i<result.length;i++){
filePath[i]=resPath+result[i].getName();
}
for(String audioPath:filePath) {
InputStream in = new FileInputStream(audioPath);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
}
}
}
请帮我。
谢谢
最佳答案
试试这个:
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
public class Main
{
public static void main(String[] args)
throws LineUnavailableException, IOException,
UnsupportedAudioFileException, InterruptedException
{
File directory = new File("res");
AudioListener listener = new AudioListener();
for(File file : directory.listFiles())
{
try(AudioInputStream stream = AudioSystem.getAudioInputStream(file); Clip clip = AudioSystem.getClip())
{
clip.addLineListener(listener);
clip.open(stream);
clip.start();
listener.waitUntilDone(); // Wait until the file has finished playing
}
}
}
private static class AudioListener implements LineListener
{
@Override
public void update(LineEvent event)
{
LineEvent.Type eventType = event.getType();
if(eventType == LineEvent.Type.STOP || eventType == LineEvent.Type.CLOSE)
{
synchronized(this)
{
notify();
}
}
}
public synchronized void waitUntilDone() throws InterruptedException
{
wait();
}
}
}
该解决方案部分基于此帖子:Trouble playing wav in Java