首页 | 注册 | 登陆
首页 >> 技术专栏 >> java文章 >> java基础 

播放一个目录下的所有声音


作者java 来源java 加入时间:2006年02月21日
摘要:
播放一个目录下的所有声音
  
import javax.sound.midi.*;
import javax.sound.sampled.*;
import …

转载:转载请保留本信息,本文来自
http://www.51dibs.com
/html/2006/article/info2/a_d6069f4c50f4db0d.htm




播放一个目录下的所有声音


站点:爱心种子小博士 关键字:播放一个目录下的所有声音




播放一个目录下的所有声音
  
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 cant 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[i]);
                    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 doesnt 
        //terminate, killing the playing thread
        try
        { Thread.sleep(500000); } catch (Exception e)
        {System.out.println("Interrupted");}
        
        //close and exit
        ssp.close();
        System.exit(0);
    }
    
}



发布人:love
→ 推荐给我的好友 → 报告错误链接
上篇文章:一个实现MD5的简洁的java类
下篇文章:java读取纯真IP数据库QQwry.dat的源...
〖文章打印〗
〖关闭窗口〗
发表评论
查看评论
中“播放一个目录下的所有声音”相关内容 中“播放一个目录下的所有声音”相关内容
中“播放一个目录下的所有声音”相关内容 中“播放一个目录下的所有声音”相关内容
中“播放一个目录下的所有声音”相关内容 中“播放一个目录下的所有声音”相关内容

关于我们网站留言友情链接与我在线与我聊天领取红包管理TOP