gpt4 book ai didi

java - 如何在JAVA中一个接一个地播放文件夹中的音频

转载 作者:行者123 更新时间:2023-12-03 01:51:31 25 4
gpt4 key购买 nike

我更喜欢使用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

关于java - 如何在JAVA中一个接一个地播放文件夹中的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39352252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com