如何在JAVA中逐个播放音频

时间:2016-09-06 15:03:15

标签: java multithreading audio

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

    }

}

请帮帮我。 感谢名单。

2 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

也可能是这种方式,但建议使用前一个答案addLineListener

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) {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(audioPath).getAbsoluteFile());
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();
            while (!clip.isRunning())
                Thread.sleep(10);
            while (clip.isRunning())
                Thread.sleep(10);
            clip.close();
        }