Overview of the "Android Basics" Multimedia Programming section

Source: Internet
Author: User

First, the use of MediaPlayer

1) How to obtain MediaPlayer instances:
You can use the direct new method:
MediaPlayer MP = new MediaPlayer ();
You can also use the Create method, such as:
MediaPlayer MP = Mediaplayer.create (this, r.raw.test);//You don't have to call Setdatasource now.



2) How to set the file to play:
MediaPlayer the file to be played consists of 3 main sources:
A. Resource resources that the user has in advance in the application
Example: Mediaplayer.create (this, r.raw.test);
B. media files stored in an SD card or other file path
For example: Mp.setdatasource ("/sdcard/test.mp3");

C. media files on the network
For example: Mp.setdatasource ("Http://www.citynorth.cn/music/confucius.mp3");

MediaPlayer's Setdatasource altogether four methods:
Setdatasource (String Path)
Setdatasource (FileDescriptor FD)
Setdatasource (context context, URI Uri)
Setdatasource (filedescriptor fd, long offset, long length)

When using FileDescriptor, you need to place the files in the Assets folder with the Res folder, and then use:
Assetfiledescriptor filedescriptor = Getassets (). OPENFD ("Rain.mp3");
M_mediaplayer.setdatasource (Filedescriptor.getfiledescriptor (), Filedescriptor.getstartoffset (), Filedescriptor.getlength ());
To set the DataSource

3) The main control method of the player:
Android controls the playback of media files by controlling the state of the player, where:
Prepare () and Prepareasync () provide both synchronous and asynchronous settings for the player to enter the prepare state, and it is important to note that if the MediaPlayer instance was created by the Create method, It is not necessary to call prepare () again before the first start of playback, because the Create method has already been called.
Start () is a way to actually start the file playback,
Pause () and stop () are relatively simple and play a role in pausing and stopping playback,


Seekto () is a positioning method that allows the player to start playing from the specified position, noting that the method is an asynchronous method, which means that the method returns does not mean that the location is complete, especially the network file being played, Onseekcomplete.onseekcomplete () is triggered when the true location is complete and can be handled by invoking the Setonseekcompletelistener (Onseekcompletelistener) Setup listener if necessary.
Release () frees the resource that the player occupies and should be called as soon as possible when the player is no longer in use.
Reset () Restores the player from the error state and resumes to the idle state.


4) Set the listener for the player:
MediaPlayer provides a number of ways to set up different listeners to better monitor the working status of the player, in order to deal with the situation in a timely manner,
such as: Setoncompletionlistener (Mediaplayer.oncompletionlistener listener),
Setonerrorlistener (Mediaplayer.onerrorlistener Listener), and so on, you need to set the player to consider when the player may appear to set up monitoring and processing logic to maintain the robustness of the player.


Second, the Soundpool summary of Android
can use the Soundpool, with Soundpool can sow some short reaction speed requires high sound,
such as the blasting sound in the game, and MediaPlayer suitable for playing long points.
1. Soundpool Loading music files uses a separate thread that does not block the operation of the UI main thread. But here if the sound file is too large to load, we may have serious consequences when we call the Play method, where Android The SDK provides a Soundpool.onloadcompletelistener class to help us understand whether the media files are loaded and finished, we reload Onloadcomplete (soundpool soundpool, int SampleID, int status) method can be obtained.
2. From the Onloadcomplete method above can be seen that the class has a number of parameters, such as ID, yes Soundpool can handle multiple media at load initialization and into memory, where efficiency is much higher than MediaPlayer.
3. The Soundpool class supports simultaneous playback of multiple sound effects, which is necessary for the game, while the MediaPlayer class is a single file that can be played synchronously.




How to use:
1. Create a Soundpool


Public soundpool (int maxstream, int streamtype, int srcquality)


maxstream--The maximum number of simultaneous streams to be played


streamtype--type of stream, typically stream_music (specifically listed in the Audiomanager Class)


srcquality--Sample rate conversion quality, currently no effect, use 0 as the default value


eg.


Soundpool soundpool = new Soundpool (3, audiomanager.stream_music, 0);


created a soundpool that supports simultaneous playback of up to 3 streams, with types marked as music.




21 like to put multiple sounds into the hashmap, such as
Soundpool = new Soundpool (4, Audiomanager.stream_music, +);
Soundpoolmap = new Hashmap<integer, integer> ();
soundpoolmap.put (1, Soundpool.load (this, R.raw.dingdong, 1));


Loading of Soundpool:
int Load (context context, int resId, int priority)//Load from APK resource
int Load (filedescriptor fd, long offset, long length, int priority)//Load from FileDescriptor object
int Load (assetfiledescriptor afd, int priority)//load from Asset object
int Load (String path, int priority)//loaded from full file path name
the last parameter is a priority.


3 plays
Play (int soundid, float leftvolume, float rightvolume, int priority, Int. loop, float rate), where leftvolume and Rightvolume represent Left and right volume, priority is prioritized, loop indicates the number of loops, rate represents
//Rate minimum 0.5 up to 2, 1 for normal speed
Sp.play (Soundid, 1, 1, 0, 0, 1);
instead of stopping, you can use the pause (int streamid) method, where both Streamid and Soundid indicate the total number in the first argument of the constructed Soundpool class, and the ID starts at 0.


Three, Android three kinds of ways to play video

1. Use the player that comes with it. Specifies that the action is action_view,data to Uri,type for its MIME type.


2, use Videoview to play. Use Videoview with Mediacontroller in the layout file to control it.


3, using MediaPlayer class and Surfaceview to achieve, this way is very flexible.


1. Call its own player

<span style= "FONT-SIZE:18PX;" >uri Uri = Uri.parse (Environment.getexternalstoragedirectory (). GetPath () + "/test_movie.m4v");  Call the system's own player     Intent Intent = new Intent (intent.action_view);     LOG.V ("URI:::::::: ()", uri.tostring ());     Intent.setdataandtype (URI, "Video/mp4");     StartActivity (Intent);</span>


2, using Videoview to achieve:
<span style= "FONT-SIZE:18PX;" >uri Uri = Uri.parse (Environment.getexternalstoragedirectory (). GetPath () + "/test_movie.m4v"); Videoview Videoview = (videoview) This.findviewbyid (R.id.video_view); Videoview.setmediacontroller (New Mediacontroller (this)); Videoview.setvideouri (URI); Videoview.start (); Videoview.requestfocus ();</span>

3. Using MediaPlayer:

<span style= "FONT-SIZE:18PX;" >public class Videosurfacedemo extends Activity implements Oncompletionlistener,onerrorlistener,oninfolistener, on Preparedlistener, onseekcompletelistener,onvideosizechangedlistener,surfaceholder.callback{private Display     Currdisplay;     Private Surfaceview Surfaceview;     Private Surfaceholder holder;     Private MediaPlayer player;     private int vwidth,vheight;                Private Boolean readytoplay = false;         public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                            This.setcontentview (R.layout.video_surface);         Surfaceview = (Surfaceview) This.findviewbyid (r.id.video_surface);         Add Callback Listener holder = Surfaceview.getholder () to Surfaceview;         Holder.addcallback (this);                    In order to play the video or use the camera preview, we need to specify its buffer type Holder.settype (surfaceholder.surface_type_push_buffers); The following begins instantiating the MediaPlayer object player = new MediAplayer ();         Player.setoncompletionlistener (this);         Player.setonerrorlistener (this);         Player.setoninfolistener (this);         Player.setonpreparedlistener (this);         Player.setonseekcompletelistener (this);         Player.setonvideosizechangedlistener (this);         LOG.V ("Begin::", "surfacedestroyed called"); Then specify the path where the file needs to be played, initialize MediaPlayer String DataPath = Environment.getexternalstoragedirectory (). GetPath () + "/test_movie.         M4V ";             try {player.setdatasource (DataPath);         LOG.V ("Next:::", "surfacedestroyed called");         } catch (IllegalArgumentException e) {e.printstacktrace ();         } catch (IllegalStateException e) {e.printstacktrace ();         } catch (IOException e) {e.printstacktrace ();     }//Then we get the current display object currdisplay = This.getwindowmanager (). Getdefaultdisplay (); } @Override public void surfacechanged (Surfaceholder arg0, int aRG1, int arg2, int arg3) {//trigger LOG.V when parameters such as surface size change ("Surface changes:::", "surfacechanged called");         } @Override public void surfacecreated (Surfaceholder holder) {//is called when surface in Surfaceview is created         Here we specify mediaplayer to play in the current surface player.setdisplay (holder);                After specifying a container for MediaPlayer playback, we can use prepare or prepareasync to prepare to play the Player.prepareasync (); } @Override public void surfacedestroyed (Surfaceholder holder) {log.v ("Surface destory:::", "s     Urfacedestroyed called ");         } @Override public void onvideosizechanged (MediaPlayer arg0, int arg1, int arg2) {//trigger when video size changes                This method triggers a log.v at least once after setting the player's source ("Video Size Change", "onvideosizechanged called");  } @Override public void Onseekcomplete (MediaPlayer arg0) {//To trigger LOG.V when the seek operation is complete ("seek completion",                "Onseekcomplete called"); } @Override PUBlic void onprepared (MediaPlayer player) {//When the prepare is complete, the method triggers, where we play the video//first get the width and height         Vwidth = Player.getvideowidth ();                    Vheight = Player.getvideoheight (); if (Vwidth > currdisplay.getwidth () | | vheight > Currdisplay.getheight ()) {//If the width or height of the video exceeds the current screen size, indent             put float wratio = (float) vwidth/(float) currdisplay.getwidth ();                            float hratio = (float) vheight/(float) currdisplay.getheight ();                            Select the large one to scale float ratio = Math.max (Wratio, hratio);             Vwidth = (int) Math.ceil ((float) vwidth/ratio);                            Vheight = (int) Math.ceil ((float) vheight/ratio);                            Set the layout parameters of the Surfaceview surfaceview.setlayoutparams (new Linearlayout.layoutparams (Vwidth, vheight));         Then start playing video Player.start (); }} @Override public boolean oninfo (MediaPlayer Player, int whatinfo, int extra) {//Trigger switch (whatinfo) {case Mediaplayer.media_i when some specific information appears or warns         Nfo_bad_interleaving:break;         Case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:break;         Case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:break;         Case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:break;     } return false; } @Override public Boolean onError (MediaPlayer player, int whaterror, int extra) {log.v ("Play Error:::",         "OnError called"); Switch (whaterror) {case MEDIAPLAYER.MEDIA_ERROR_SERVER_DIED:LOG.V ("Play ERROR:::", "Media_error_ser             Ver_died ");         Break             Case MEDIAPLAYER.MEDIA_ERROR_UNKNOWN:LOG.V ("Play ERROR::", "Media_error_unknown");         Break         Default:break;     } return false; } @Override public void Oncompletion (MediaPlayer player) {//when MediAplayer triggers log.v ("Play Over::", "oncomletion called") after playback is complete;     This.finish (); }}</span>


Overview of the "Android Basics" Multimedia Programming section

Related Article

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.