Instance parsing using Java to implement basic audio player writing Essentials _java

Source: Internet
Author: User

Java audio playback, because you have to rely on the local environment, so Java has little advantage in audio processing, or since the Java system development is not too much to consider audio playback factors, to know the first version of Java 1.1, No later Javax.sound package, audio can only be transferred through the applet package ...

Unfortunately, in the graphics program development, our program is also unavoidable to use the background music, the effect of sound and other images with the operation, Ah, this is really the sun God gave us a not to play a big joke. Fortunately, sun big God eyes, provided the Javax.sound package, only to save us in the abyss of misery ~

But the problem followed is that in the use of javax.sound packages, as in the Java Multimedia Tool class, it does not provide a perfect release mechanism. If we do Windows development, call MediaPlayer repeated n times may not be a big deal, but in Java, if the audio program running repeatedly, it is very easy to have memory cumulative loss of the situation, So that I finally throw a java.lang.OutOfMemoryError, and then ... The program hangs, the user is silly, we are crazy ...

This is already "can endure is not tolerated" problem, in view of this, so in my loonframework framework development, two times integrated sound under the relevant methods, and strive to the simplest code, make the most perfect audio control class. In Loonframework-game has not yet become a big now, first extract a part of the method, for you reader--PAT Bricks!

corresponding to the network resource call, in Loonframework set up its own URI class, the basic contents are as follows:
(where Streamhelper is the Loonframework's own streaming media control class, Gethttpstream method please replace it yourself.) )

Package org.loon.framework.game.net;

Import Org.loon.framework.game.helper.StreamHelper; /** *//** * <p> * title:loonframework * </p> * <p> * description:loonframework special URI (Uniform Resource Identifier) * &L
 t;/p> * <p> * Copyright:copyright (c) 2007 * </p> * <p> * company:loonframework * </p> * * @author Chenpeng * @email: ceponline@yahoo.com.cn * @version 0.1/public class URI ...

  {//Transport protocol type public static final int _l_uri_http = 1;

  public static final int _l_uri_udp = 2;

  Private String _uri;

  private int _type; /** *//** * destructor for injecting URI and type * * @param uri * @param type/public uri (String uri, int type) ...
    {_uri = new String (URI);
  _type = type; /** *//** * destructor for injecting URI * * @param uri/public uri (String URI) ...
    {_uri = new String (URI);
  _type = uri._l_uri_http;
   /** *//** * Returns a byte array of the resource where the URI is located. * * @return/public byte[] GetData () ... {if (_uri = null) ...
    {return null;
  Return Streamhelper.gethttpstream (_uri); Public String GetURI () ...
  {return _uri; public int GetType () ...
  {return _type;

In the Loonframework framework, a basic Sounddata class is customized to manage audio data sources uniformly.

Package org.loon.framework.game.sound;
Import Org.loon.framework.game.helper.StreamHelper;

Import Org.loon.framework.game.net.URI; /** *//** * <p> * title:loonframework * </p> * <p> * Description: For access to and caching of sound file data (see Loonframe for further content operations) Work-game Framework) * </p> * <p> * Copyright:copyright (c) 2007 * </p> * <p> * Company:loonframew 

  ORK * </p> * * @author Chenpeng * @email: ceponline@yahoo.com.cn * @version 0.1/public class sounddata ...

  Private byte[] _data;

  Private Boolean _loop;

  private int _type;

  public static final int _l_soundtype_midi = 1;

  public static final int _l_soundtype_wav = 2; /** *//** * destructor to inject uri,type,loop * * @param URI * @paramType * @param loop */public Sounddata (URI uri, int type, Boolean loop) ... {if (URI!= null) ...
    {_data = Uri.getdata ();
    } _type = type;
  _loop = loop; /** *//** * destructor to inject data,type,loop * * @param data * @param type * @param loop/public Soun Ddata (byte[] data, int type, Boolean loop) ... {if (data!= null && data.length > 0) ...
      {_data = new byte[data.length];
    Direct copy byte array system.arraycopy (data, 0, _data, 0, _data.length);
    } _type = type;
  _loop = loop;  /** *//** * destructor to inject Resname,type,loop * @param resname * @param type * @param loop/Public Sounddata (String resname, int type, Boolean loop) ...
  {This (Streamhelper.getdatasource (resname), type,loop); Public byte[] GetData () ...
  {return _data; public boolean getloop () ...
  {return _loop; public void Setloop (Boolean loop) ...
  {_loop = loop; public int gEttype () ...
  {return _type;

 }

}

Loonframework audio Playback related methods, encapsulation and soundplay, programmers can ignore javax.sound internal details, and directly call Soundplay to complete the relevant operations.

Package org.loon.framework.game.sound;

Import Java.io.ByteArrayInputStream;
Import Javax.sound.midi.MetaEventListener;
Import Javax.sound.midi.MetaMessage;
Import Javax.sound.midi.MidiSystem;
Import javax.sound.midi.Sequence;
Import Javax.sound.midi.Sequencer;
Import Javax.sound.sampled.AudioFileFormat;
Import Javax.sound.sampled.AudioSystem;
Import Javax.sound.sampled.Clip;

Import Javax.sound.sampled.DataLine;

Import Org.loon.framework.game.net.URI; /** *//** * <p> * title:loonframework * </p> * <p> * Description: For sound file operation (only part of the method in Loonframework, more See Loonframework-game framework for details] * </p> * <p> * Copyright:copyright (c) 2007 * </p> * <p> * compa Ny:loonframework * </p> * * @author Chenpeng * @email: ceponline@yahoo.com.cn * @version 0.1/public class Soundplay implements Metaeventlistener, Runnable ...

  {private int _sleeptime;

  Private Clip _audio;

  Private sequencer _midi;

  Private Boolean _loop; private int_soundtype;

  Private Boolean _playing;

  Private Thread _thread = null;

  Private Boolean _isrun = false; /** *//** * destructor, Initialize Soundplay */public soundplay () ...
    {_loop = false;
    _soundtype = 0;
    _sleeptime = 1000;

  _playing = false; //Load sound files public boolean load (Sounddata data) ...
    {Reset (); if (data = null | | data.getdata () = null) ...
    {return false;
  Return init (Data.getdata (), Data.gettype (), Data.getloop ());  /** *//** * Directly play URL file * * @param uri * @param ftype * @param loop * @return/public Boolean Load (URI uri, int ftype, Boolean loop) ...
    {//Refresh data reset (); if (URI = = null) ...
    {return false;
    }//Get sounddata sounddata data = new Sounddata (URI, ftype, loop); if (data = null | | data.getdata () = null) ...
    {return false;

  Return init (Data.getdata (), Data.gettype (), Data.getloop ()); /** *//** * Initialize sound related data * * @pAram Data * @param ftype * @param loop * @return * * Private Boolean init (byte[) data, int ftype, Boolean loo P) ...

    {Boolean result = false;

    Bytearrayinputstream bis = null; Try ...
    {bis = new bytearrayinputstream (data); catch (Exception e) ...
    {bis = null; } if (bis = null) ...
    {return false; }//Judge type switch (ftype) ... {//MIDI case SOUNDDATA._L_SOUNDTYPE_MIDI:///When MIDI does not exist if (_midi = null) ... {Try ...
          {//Get sequencer _midi = Midisystem.getsequencer ();

        _midi.open (); catch (Exception ex) ...
        {_midi = null; } if (_midi!= null) ...
        {_midi.addmetaeventlistener (this); }///When MIDI is still not available if (_midi!= null) ...

        {//re-create Sequence Sequence sc = null; Try ...
        {sc = midisystem.getsequence (bis); catch (Exception e) ... {sc = null;
        } if (sc!= null) ... {Try ...

            {_midi.setsequence (SC);

            Gets whether the loop plays _loop = loop;

          Gets whether the load result = true; catch (Exception ee) ...

        {}//get sound type _soundtype = Sounddata._l_soundtype_midi; } Try ...
      {Bis.close (); catch (Exception ee) ...

    {} break;

      Wav case Sounddata._l_soundtype_wav:audiofileformat type = null; Get Audio Try ...
      {type = Audiosystem.getaudiofileformat (bis); catch (Exception e) ...
      {type = null; //Close Stream Try ...
      {Bis.close (); catch (Exception ex) ... {} if (type = null) ...
      {return false;

      The information object that constructs the data row based on the specified information dataline.info di = new Dataline.info (Clip.class, Type.getformat ()); Switch to clip Try ... {_audio = (Clip) audiosystem.getline (DI);
      catch (Exception e) ... {}//Play file Try ...

        {_audio.open (Type.getformat (), data, 0, data.length);

        _loop = loop;

      result = true; catch (Exception e) ...

      {}//Get file type _soundtype = Sounddata._l_soundtype_wav;

    Break
  return result; public Boolean play (Sounddata data) ... {if (!load (data)) ...
    {return false;

  Return to play (); public boolean play () ... {switch (_soundtype) ... {Case Sounddata._l_soundtype_midi:try ...

        {_midi.start ();

        _playing = true;

      _soundtype = Sounddata._l_soundtype_midi; catch (Exception ee) ...

    {} break; Case Sounddata._l_soundtype_wav:if (_audio!= null) ... {if (_loop) ...
          {//Set loop _audio.setlooppoints (0,-1);

          _audio.setframeposition (0);

        _audio.loop (clip.loop_continuously); else ... {

          // Force setting playback position to 0 _audio.setframeposition (0);

        _audio.start ();

      } _playing = true;

    } break;

  return _playing;
   /** *//** * AutoPlay, end after loop stop. * * @param data * @return/public boolean autoplay (Sounddata data) ... {if (!load (data)) ...
    {return false;
  return AutoPlay ();
   /** *//** * AutoPlay, end after loop stop. * * @return/public boolean autoplay () ...
    {_isrun = true;
    _thread = new Thread (this);
    _thread.start ();
  return _playing; /** *//** * Stop playing */public void stop () ... {if (_audio!= null && _audio.isactive ()) ... {Try ...
      {_audio.stop (); catch (Exception e) ... {}} if (_midi!= null) ...
    {_midi.stop ();
    } _playing = false;
  _isrun = false; /** *//** * Release data */public void reset () ...

    {Stop ();
    _loop = false;

    _soundtype = 0; if (_midi!= null) ...{_midi.close ();

    _midi = null; } if (_audio!= null && _audio.isopen ()) ...

      {_audio.close ();

    _audio = null;
    } _isrun = false;
  _thread = null; /** *//** * Set metamessage/public void meta (metamessage meta) ...  {//Determine whether to loop the MIDI if (_loop && _soundtype = = Sounddata._l_soundtype_midi && meta.gettype () = = 47) ... {if (_midi!= null && _midi.isopen ()) ...
        {_midi.setmicrosecondposition (0);

      _midi.start (); }} public void Run () ... {while (_isrun) ...
      {Play ();
      Because the playback type is unique, only one _playing result is returned to determine. if (_midi!= null) ...
      {_playing = _midi.isrunning (); } if (_audio!= null) ...
      {_playing = _audio.isrunning (); //When play stop if (!_playing) ...
      {//release reset (); Try ...
      {Thread.Sleep (_sleeptime); catch (Interruptedexception e) ...
       { E.printstacktrace (); }} public int getsleeptime () ...
  {return _sleeptime;
   /** *//** * Sets the AutoPlay thread cycle time. * * @param time/public void setsleeptime (int time) ...
  {_sleeptime = time;

 }
}

What we need to deal with is sounddata data and soundplay operations encapsulated as entities without having to deal with complicated javax.sound.

The method is invoked as follows:

Package org.test;
Import Org.loon.framework.game.helper.StreamHelper;
Import Org.loon.framework.game.net.URI;
Import Org.loon.framework.game.sound.SoundData;

Import Org.loon.framework.game.sound.SoundPlay; /** *//** * <p>Title:LoonFramework</p> * <p>description:soundplay playback Test </p> * <p>copyrigh T:copyright (c) 2007</p> * <p>Company:LoonFramework</p> * @author Chenpeng * @email: Ceponline@yaho o.com.cn * @version 0.1 * * public class soundplaytest ... {static void Selectplay (int ftype) ...
    
    {Sounddata data=null; Switch (ftype) ... {//The music case 0:data=new Sounddata ("New Uri" ("http://looframework.sourceforge.net/midi/") is played through the Loonframework URI from the network
      Who is the big hero. Mid "), Sounddata._l_soundtype_midi,false);
    Break
      Byte[of music files through local resources] objects play music case 1:byte[] Bytes=streamhelper.getresourcedata ("/midi/who is Big Hero. Mid");
      Data=new Sounddata (Bytes,sounddata._l_soundtype_midi,false);
      Break Play music through the music file path 
    Case 2:data=new Sounddata ("c:/who is the Big hero. Mid", sounddata._l_soundtype_midi,false);
    Break
    } soundplay play=new Soundplay ();
    The difference between AutoPlay and play method is that AutoPlay playback will automatically stop and release resources, plays need to manually stop.
    Play.play (data); Play.
  AutoPlay (data); public static void Main (String[]args) ...
  {Selectplay (2);

 }
  
}

A more detailed approach will be followed by an explanation after the loonframework-game is fully publicized.

Another: Because Streamhelper Association other loonframework in the method, temporarily do not give, InputStream to byte[] can be written as follows:

is for the InputStream

  bytearrayoutputstream bytearrayoutputstream = new Bytearrayoutputstream ();
Used to undertake byte[]
    byte[] arraybyte = null;
    Try ... {
      //each transmission size is 4096
      byte[] bytes = new byte[4096];
      bytes = new byte[is.available ()];
      int read;
      while (read = Is.read (bytes)) >= 0) ... {
        bytearrayoutputstream.write (bytes, 0, read);
      }
      Arraybyte = Bytearrayoutputstream.tobytearray ();
    } catch (IOException e) ... {return
      null;
    } Finally ... {
      Try ... {
        if (bytearrayoutputstream!= null) ... {
          bytearrayoutputstream.close ();
          Bytearrayoutputstream = null;
        }
        if (is!= null) ... {
          is.close ();
          is = null;
        }

      } catch (IOException e) ... {
      }
    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.