⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 audioengine.java

📁 M3DEA (Mobile 3D Engine API) 手机3D引擎API
💻 JAVA
字号:
/*
 *M3DEA - MOBILE 3D ENGINE API
 *Copyright (C) 2006 Alexandre Watanabe         alexandre_sw@yahoo.com.br     
 *		     Diego de Freitas           zenon_cc@yahoo.com.br
 *		     Paulo Rodrigo Priszculnik  paulorp@paulorp.trix.net
 *		     Rodrigo Arthur Lopes       raspl@terra.com.br
 *
 * This library is free software; you can redistribute it 
 * and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 *
 * This library is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE. See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to
 * the Free Software Foundation, Inc., 59 Temple Place, Suite
 * 330, Boston, MA 02111-1307 USA
 *
 */

package m3dea.audio;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
import java.io.*;

/**
 * Classe que gerencia os 醬dios que est鉶 em executa玢o
 */
public class AudioEngine
{
    private Hashtable audios;
    
    private static AudioEngine audioengine = null;
    private Thread thread = null;
        
    
    private AudioEngine()
    {
        audios = new Hashtable();
        
        thread = new Thread( new Runnable()
        {
            public void run()
            {
                while(true)
                {
                    removeAudios();
                    try
                    {
                        
                        Thread.sleep(3 * 1000); // 3 segundos
                    } catch (InterruptedException ex)
                    {
                        ex.printStackTrace();
                    } // 3 segundos
                }
            }
        });
        thread.start();
    }
    
    /**
     * Recupera inst鈔cia da classe
     * @return inst鈔cia da classe
     */
    public static AudioEngine getInstance()
    {
        if(audioengine == null) audioengine = new AudioEngine();
        return audioengine;
    }
    
    /**
     * Coloca 羥dio para ser executado
     * @param audio 羥dio a ser executado
     */
    public void play(Audio audio)
    {
        play(audio, 100);
    }
    
    /**
     * P醨a de tocar 醬dio caso ele ainda esteja tocando
     * @param audio 醬dio a ser parado
     */
    public void stop(Audio audio)
    {
        AudioPlayer ap = (AudioPlayer) audios.get(audio);
        if(ap == null) return;
        
        ap.stopSound();
        audios.remove(audio);
    }
    /**
     * P醨a e remove todos os audios que est鉶 tocando
     */
    public void stopAll()
    {
        Enumeration en = audios.keys();
        while( en.hasMoreElements() )
            stop( (Audio) en.nextElement() );
    }
    
    /**
     * Coloca 羥dio para ser executado
     * @param audio 羥dio a ser executado
     * @param volume Volume do 醬dio
     */
    public void play(Audio audio, int volume)
    {
        AudioPlayer novo = null;
        if(audio instanceof FileAudio)
        {
            novo = new AudioPlayer(((FileAudio)audio).getMusicPath());
            novo.playFile(audio.getLoopCount());
        }
        else if( audio instanceof ToneAudio )
        {
            ToneAudio tone = (ToneAudio)audio;
            novo = new AudioPlayer(tone.getTone(), tone.getMs(), volume);
            novo.playTone();
        }
        else if( audio instanceof ListToneAudio )
        {
            novo = new AudioPlayer(((ListToneAudio)audio).getList());
            novo.playListTone(audio.getLoopCount());
        }
        
        if(novo == null) return;
        
        audios.put(audio, novo);
    }
    
    /* Remove os audios que n鉶 est鉶 mais em execu玢o */
    private void removeAudios()
    {
        Enumeration en = audios.keys();
        while( en.hasMoreElements() )
        {
            Audio a = (Audio) en.nextElement();
            AudioPlayer ap = (AudioPlayer) audios.get( a );
            if( ap.isInterrupted() ) stop( a );
        }
           
    }
    
}

/**
 * Classe utilizada pela AudioEngine para executar o 羥dio
 */
class AudioPlayer
{
    private Player player;
    private String musicPath;
    private int tone;
    private int ms;
    private int volume;
    private byte list_tone[];
    
    private boolean interrupted = false;
        
    /**
     * Cria uma nova inst鈔cia de AudioPlayer para tocar um Tone
     * @param tone o tone a ser tocado (int de 0 a 127)
     * @param ms dura玢o (em milisegundos)
     * @param volume volume (0 a 100)
     */
    public AudioPlayer(int tone, int ms, int volume)
    {
        this.tone = tone;
        this.ms = ms;
        this.volume = volume;
    }
    
    /**
     * Cria uma nova inst鈔cia de AudioPlayer para tocar uma Lista de Tone
     * @param list_tone lista de tones
     */
    public AudioPlayer(byte list_tone[])
    {
        this.list_tone = list_tone;
    }
    
    /**
     * Cria uma nova inst鈔cia de AudioPlayer para tocar um arquivo
     * @param musicPath caminho do arquivo
     */
    public AudioPlayer(String musicPath)
    {
        this.musicPath = musicPath;
        
    }
    
    /**
     * Toca o Tone
     */
    public void playTone()
    {
        try
        {
            Manager.playTone(tone,ms,volume);
        }
        catch (MediaException ex)
        {
            System.out.println("can't play tone");
        }
    }
    
    /**
     * Toca a lista de Tone
     * @param loopCount quantidade de vezes a ser executado
     */
    public void playListTone(int loopCount)
    {
        try
        {
            player = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR);
            if(loopCount != -1) player.addPlayerListener(new StopListener());
            player.realize();
            ToneControl tc = (ToneControl)player.getControl("javax.microedition.media.control.ToneControl");
            tc.setSequence(list_tone);
            player.setLoopCount(loopCount);
            player.start();
        }
        catch (IOException ioe)
        {
            System.err.println(ioe.getMessage());
        }
        catch (MediaException me)
        {
            System.err.println(me.getMessage());
        }
    }
    
    /**
     * Toca o Arquivo configurado anteriormente
     * @param loopCount quantidade de vezes a ser executado
     */
    public void playFile(final int loopCount)
    {
        Thread t = new Thread(){
        public void run(){
        try
        {
            if (musicPath.startsWith("http:"))
            {
                player = Manager.createPlayer(musicPath);
            }
            else
            {
                InputStream is = this.getClass().getResourceAsStream(musicPath);
                player = Manager.createPlayer(is, getMIME(musicPath));
                if(loopCount != -1) player.addPlayerListener(new StopListener());
                player.realize();
            }
            player.setLoopCount(loopCount);
            player.start();
        }
        catch(Exception e)
        {
            if (player != null)
            {
                player.close();
                player = null;
            }
        }
        }
        };
       t.start();
    }
    
    /**
     * P醨a de executar o 醬dio
     */
    void stopSound()
    {
        try
        {
            if (player != null)
            {
                player.deallocate();
                player.close();
                player = null;
                interrupted = true;
            }
        } catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
    
    /**
     * Devolve o mime do arquivo de 醬dio
     * @param mpath caminho do arquivo de 醬dio
     */
    private String getMIME(String mpath) throws Exception
    {
        String mime;
        if (mpath.endsWith("wav"))
        {
            mime = "audio/x-wav";
        }
        else if (mpath.endsWith("jts"))
        {
            mime = "audio/x-tone-seq";
        }
        else if (mpath.endsWith("mid"))
        {
            mime = "audio/midi";
        }
        else if(mpath.endsWith("au"))
        {
            mime = "audio/basic";
        }
        else if(mpath.endsWith("mp3"))
        {
            mime = "audio/mpeg";
        }
        else
        {
            throw new Exception("Cannot guess content type from URL: "+mpath);
        }
        return mime;
    }
    
        
    private class StopListener implements PlayerListener
    {        
        public void playerUpdate(Player player, String event, Object eventData)
        {
            try
            {
                if (event.equals(STOPPED) || event.equals(STOPPED_AT_TIME) ||
                        event.equals(ERROR) ||
                        event.equals(END_OF_MEDIA))
                {
                    player.deallocate();
                    player.close();
                    player = null;
                    interrupted = true;
                    
                }
                else if (event.equals(DEVICE_UNAVAILABLE))
                {
                    player.stop();
                    interrupted = true;
                }
                else if (event.equals(DEVICE_AVAILABLE))
                {
                    player.start();
                }                
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    public boolean isInterrupted()
    {
        return interrupted;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -