Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 364|回复: 0

[Java基础知识]播放一个目录下的所有声音

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-1 04:51:47 | 显示全部楼层 |阅读模式
    import javax.sound.midi.*;
    import javax.sound.sampled.*;
    import java.io.File;
    import java.io.InputStream;
    import java.io.FileInputStream;
    import java.io.BufferedInputStream;
    import java.util.Vector;
    import java.net.URL;


    /**
      * A simple player for sampled sound files.
      *
      *
      * @author Steve Potts
      */  
      
       
       
       

       
      

    public class SimpleSoundPlayer implements Runnable, LineListener, MetaEventListener
    {
          
         final int bufSize = 16384;
          
         Vector sounds = new Vector();
         Thread thread;
         Sequencer sequencer;
         boolean midiEOM, audioEOM;
         Synthesizer synthesizer;
         MidiChannel channels[];
         Object currentSound;
         String currentName;
         double duration;
         int num;
         boolean bump;
         boolean paused = false;
          
         String errStr;
          
          
         public void open()
         {
             try
             {
                 sequencer = MidiSystem.getSequencer();
                  
                 if (sequencer instanceof Synthesizer)
                 {
                     synthesizer = (Synthesizer)sequencer;
                     channels = synthesizer.getChannels();
                 }
                  
             } catch (Exception ex)
             { ex.printStackTrace(); return; }
             sequencer.addMetaEventListener(this);
             
         }
          
          
         public void close()
         {
             if (sequencer != null)
             {
                 sequencer.close();
             }
         }
          
         private void addSound(File file)
         {
             sounds.add(file);
         }
          
          
         public boolean loadSound(Object object)
         {
             duration = 0.0;
             
             currentName = ((File) object).getName();
             try
             {
                 currentSound = AudioSystem.getAudioInputStream((File) object);
             } catch(Exception e1)
             {
                 try
                 {
                     FileInputStream is = new FileInputStream((File) object);
                     currentSound = new BufferedInputStream(is, 1024);
                 } catch (Exception e3)
                 {
                     e3.printStackTrace();
                     currentSound = null;
                     return false;
                 }
                 //}
             }
             
             // user pressed stop or changed tabs while loading
             if (sequencer == null)
             {
                 currentSound = null;
                 return false;
             }
             
             if (currentSound instanceof AudioInputStream)
             {
                 try
                 {
                     AudioInputStream stream = (AudioInputStream) currentSound;
                     AudioFormat format = stream.getFormat();
                      
                     /**
                      * we can"t yet open the device for ALAW/ULAW playback,
                      * convert ALAW/ULAW to PCM
                      */
                      
                     if ((format.getEncoding() == AudioFormat.Encoding.ULAW) ||
                     (format.getEncoding() == AudioFormat.Encoding.ALAW))
                     {
                         AudioFormat tmp = new AudioFormat(
                         AudioFormat.Encoding.PCM_SIGNED,
                         format.getSampleRate(),
                         format.getSampleSizeInBits() * 2,
                         format.getChannels(),
                         format.getFrameSize() * 2,
                         format.getFrameRate(),
                         true);
                         stream = AudioSystem.getAudioInputStream(tmp, stream);
                         format = tmp;
                     }
                     DataLine.Info info = new DataLine.Info(
                     Clip.class,
                     stream.getFormat(),
                     ((int) stream.getFrameLength() *
                     format.getFrameSize()));
                      
                     Clip clip = (Clip) AudioSystem.getLine(info);
                     clip.addLineListener(this);
                     clip.open(stream);
                     currentSound = clip;
                     //seekSlider.setMaximum((int) stream.getFrameLength());
                 } catch (Exception ex)
                 {
                     ex.printStackTrace();
                     currentSound = null;
                     return false;
                 }
             } else if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream)
             {
                 try
                 {
                     sequencer.open();
                     if (currentSound instanceof Sequence)
                     {
                         sequencer.setSequence((Sequence) currentSound);
                     } else
                     {
                         sequencer.setSequence((BufferedInputStream) currentSound);
                     }
                      
                 } catch (InvalidMidiDataException imde)
                 {
                     System.out.println("Unsupported audio file.");
                     currentSound = null;
                     return false;
                 } catch (Exception ex)
                 {
                     ex.printStackTrace();
                     currentSound = null;
                     return false;
                 }
             }
             
             duration = getDuration();
             
             return true;
         }
          
          
         public void playSound()
         {
             midiEOM = audioEOM = bump = false;
             if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream && thread != null)
             {
                 sequencer.start();
                 while (!midiEOM && thread != null && !bump)
                 {
                     try
                     { thread.sleep(99); } catch (Exception e)
                     {break;}
                 }
                 sequencer.stop();
                 sequencer.close();
             } else if (currentSound instanceof Clip)
             {
                 Clip clip = (Clip) currentSound;
                 clip.start();
                 try
                 { thread.sleep(99); } catch (Exception e)
                 { }
                 while ((paused || clip.isActive()) && thread != null && !bump)
                 {
                     try
                     { thread.sleep(99); } catch (Exception e)
                     {break;}
                 }
                 clip.stop();
                 clip.close();
             }
             currentSound = null;
         }
          
          
         public double getDuration()
         {
             double duration = 0.0;
             if (currentSound instanceof Sequence)
             {
                 duration = ((Sequence) currentSound).getMicrosecondLength() / 1000000.0;
             }  else if (currentSound instanceof BufferedInputStream)
             {
                 duration = sequencer.getMicrosecondLength() / 1000000.0;
             } else if (currentSound instanceof Clip)
             {
                 Clip clip = (Clip) currentSound;
                 duration = clip.getBufferSize() /
                 (clip.getFormat().getFrameSize() * clip.getFormat().getFrameRate());
             }
             return duration;
         }
          
          
         public void update(LineEvent event)
         {
             if (event.getType() == LineEvent.Type.STOP && !paused)
             {
                 audioEOM = true;
             }
         }
          
          
         public void meta(MetaMessage message)
         {
             if (message.getType() == 47)
             {  // 47 is end of track
                 midiEOM = true;
             }
         }
          
          
         private void reportStatus(String msg)
         {
             if ((errStr = msg) != null)
             {
                 System.out.println(errStr);
              }
         }
          
          
         public Thread getThread()
         {
             return thread;
         }
          
         public void start()
         {
             thread = new Thread(this);
             thread.setName("SimpleSamplePlayer");
             thread.start();
         }
          
         public void stop()
         {
             if (thread != null)
             {
                 thread.interrupt();
             }
             thread = null;
         }
          
         public void run()
         {
             for (; num < sounds.size() && thread != null; num++)
             {
                 if( loadSound(sounds.get(num)) == true )
                 {
                     playSound();
                 }
                 // take a little break between sounds
                 try
                 { thread.sleep(222); } catch (Exception e)
                 {break;}
             }
             num = 0;
             
             thread = null;
             currentName = null;
             currentSound = null;
             System.out.println("Press <ctrl-c> to exit");
         }
          
         public void loadSounds(String name)
         {
             try
             {
                 File file = new File(name);
                 if (file != null && file.isDirectory())
                 {
                     String files[] = file.list();
                     for (int i = 0; i < files.length; i++)
                     {
                         File leafFile = new File(file.getAbsolutePath(), files);
                         addSound(leafFile);
                     }
                 }
             } catch (Exception e)
             {
                 System.out.println("Exception " + e);
             }
         }
          
         public static void main(String args[])
         {
             //every file in this directory will be played
             String media = "sounds";
             
             final SimpleSoundPlayer ssp = new SimpleSoundPlayer();
             ssp.open();
       
             //we first load the sound file names in a vector
             ssp.loadSounds(media);
             
             
             //Then we start a thread to play the sounds
             ssp.start();
             
             //We have to wait for a while so that the process doesn"t  
             //terminate, killing the playing thread
             try
             { Thread.sleep(500000); } catch (Exception e)
             {System.out.println("Interrupted");}
             
             //close and exit
             ssp.close();
             System.exit(0);
         }
          
    }

      

      
      
       
       

         
       

         
       
      



    源码下载:http://file.javaxxz.com/2014/10/1/045146531.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-2 05:06 , Processed in 0.410118 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表