[Android Basics] multimedia programming section, android multimedia

Source: Internet
Author: User

[Android Basics] multimedia programming section, android multimedia

I. Use MediaPlayer

1) how to obtain a MediaPlayer instance:
You can use the new method directly:
MediaPlayer mp = new MediaPlayer ();
You can also use the create method, such:
MediaPlayer mp = MediaPlayer. create (this, R. raw. test); // you do not need to call setDataSource.
 
 
 
2) how to set the file to be played:
MediaPlayer files to be played mainly include three sources:
A. resource provided by the user in the Application
Example: MediaPlayer. create (this, R. raw. test );
B. Media files stored in SD cards or other file paths
For example: mp. setDataSource ("/sdcard/testcard ");
 
C. Media files on the network
Example: mp. setDataSource ("http://www.citynorth.cn/music/confucius.mp3 ");
 
The setDataSource of MediaPlayer has four methods:
SetDataSource (String path)
SetDataSource (FileDescriptor fd)
SetDataSource (Context context, Uri uri)
SetDataSource (FileDescriptor fd, long offset, long length)
 
When FileDescriptor is used, you need to put the file in the assets folder at the same level as the res folder, and then use:
AssetFileDescriptor fileDescriptor = getAssets (). openFd ("rainsets ");
M_mediaPlayer.setDataSource (fileDescriptor. getFileDescriptor (), fileDescriptor. getStartOffset (), fileDescriptor. getLength ());
To set datasource
 
3) main player control methods:
Android controls the playback of media files by controlling the player status:
Prepare () and prepareAsync () provide two synchronous and asynchronous methods to set the player to enter the prepare status. Note that if the MediaPlayer instance is created by the create method, therefore, you do not need to call prepare () before starting the playback for the first time, because prepare () has been called in the create method.
Start () is the method for truly starting file playback,
Pause () and stop () are relatively simple and play the role of pausing and stopping playback,


SeekTo () is a positioning method that allows the player to start playing from the specified position. It should be noted that this method is an Asynchronous Method. That is to say, when this method is returned, it does not mean that the positioning is complete, in particular, the OnSeekComplete is triggered when the network file is located. onSeekComplete (). If needed, you can call setOnSeekCompleteListener (OnSeekCompleteListener) to set the listener for processing.
Release () can release the resources occupied by the player. Once it is determined that the player is no longer used, it should be called to release the resources as soon as possible.
Reset () enables the player to recover from the Error state and then return to the Idle state.


4) set the player listener:
MediaPlayer provides some ways to set different listeners to better monitor the player's working status, in order to timely handle various situations,
For example, setOnCompletionListener (MediaPlayer. OnCompletionListener listener ),
SetOnErrorListener (MediaPlayer. OnErrorListener listener) and so on. When you set the player, you must set the listening and processing logic to ensure the robustness of the player.


Ii. Summary of soundpool in Android
Soundpool can be used, and soundpool can be used to play a few short sounds with high response speed requirements,
For example, in the game, the burst sound, and mediaplayer is suitable for playing long points.
1. The SoundPool uses an independent thread to load music files and does not block operations in the main UI thread. However, if the audio file is too large to be loaded, we may have serious consequences when calling the play method. Here, the Android SDK provides a SoundPool. the OnLoadCompleteListener class helps us understand whether a media file is loaded. We can obtain it by reloading the onLoadComplete (SoundPool soundPool, int sampleId, int status) method.
2. from the above onLoadComplete method, we can see that this class has many parameters, such as id. Yes, SoundPool can process multiple media initialization at a time during load and put it into the memory, which is much more efficient than MediaPlayer.
3. The SoundPool class supports playing multiple sound effects at the same time, which is necessary for the game, while the MediaPlayer class supports playing only one file and one file simultaneously.




Usage:
1. Create a SoundPool


Public SoundPool (int maxStream, int streamType, int srcQuality)


MaxStream -- maximum number of streams simultaneously played


StreamType -- stream type, which is generally STREAM_MUSIC (listed in the AudioManager class)


SrcQuality -- sampling rate conversion quality. No effect currently. Use 0 as the default value.


Eg.


SoundPool soundPool = new SoundPool (3, AudioManager. STREAM_MUSIC, 0 );


Creates a SoundPool that supports simultaneous playback of up to three streams and marks the type as music.




2. Put multiple voices in HashMap, for example
SoundPool = new SoundPool (4, AudioManager. STREAM_MUSIC, 100 );
SoundPoolMap = new HashMap <Integer, Integer> ();
SoundPoolMap. put (1, soundPool. load (this, R. raw. dingdong, 1 ));


Loading soundpool:
Int load (Context context, int resId, int priority) // load data from the APK Resource
Int load (FileDescriptor fd, long offset, long length, int priority) // load data from the FileDescriptor object
Int load (AssetFileDescriptor afd, int priority) // load data from the Asset object
Int load (String path, int priority) // load data from the complete file path
The last parameter is the priority.


3. Play
Play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate), where leftVolume and rightVolume indicate the Left and Right volume, priority indicates the priority, and loop indicates the number of cycles, rate indicates the rate, as shown in figure
// The lowest speed is 0.5. The highest speed is, indicating the normal speed.
Sp. play (soundId, 1, 1, 0, 0, 1 );
The pause (int streamID) method can be used to stop the operation. The streamID and soundID indicate the total number in the first parameter for constructing the SoundPool class, And the id starts from 0.


3. Three video playback methods for Android

1. Use its own player. Specify Action as ACTION_VIEW, Data as Uri, and Type as its MIME Type.


2. Use VideoView for playback. In the layout file, use VideoView and MediaController to control it.


3. Use the MediaPlayer class and SurfaceView. This method is flexible.


1. Call its own player

<Span style = "font-size: 18px;"> Uri uri = Uri. parse (Environment. getExternalStorageDirectory (). getPath () + "/Test_Movie.m4v"); // call the built-in player Intent intent = new Intent (Intent. ACTION_VIEW); Log. v ("URI:", uri. toString (); intent. setDataAndType (uri, "video/mp4"); startActivity (intent); </span>


2. Use VideoView to implement:
<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. Use MediaPlayer:

<Span style = "font-size: 18px;"> public class VideoSurfaceDemo extends Activity implements OnCompletionListener, OnErrorListener, OnInfoListener, OnPreparedListener, OnSeekCompleteListener, listener, 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 to surfaceView. getHolder (); holder. addCallback (this); // to play a video or use Camera preview, We need to specify its Buffer type holder. setType (SurfaceHolder. SURFACE_TYPE_PUSH_BUFFERS); // 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"); // specify the path of the file to be played and 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 obtain the current Display object currDisplay = this. getWindowManager (). getdefadisplay display () ;}@ Override public void surfaceChanged (SurfaceHolder arg0, int arg1, int arg2, int arg3) {// trigger Log when parameters such as Surface size change. v ("Surface Change:", "surfaceChanged called") ;}@ Override public void surfaceCreated (SurfaceHolder holder) {// called when the Surface in SurfaceView is created // here we specify MediaPlayer to play the player in the current Surface. setDisplay (holder); // After the Media player container is specified, we can use prepare or prepareAsync to prepare the player. prepareAsync () ;}@ Override public void surfaceDestroyed (SurfaceHolder holder) {Log. v ("Surface Destory:", "surfaceDestroyed called") ;}@ Override public void onVideoSizeChanged (MediaPlayer arg0, int arg1, int arg2) {// triggered when the video size changes. // This method triggers a Log at least once after the player source is set. v ("Video Size Change", "onVideoSizeChanged called") ;}@ Override public void onSeekComplete (MediaPlayer arg0) {// Log is triggered when the seek operation is completed. v ("Seek Completion", "onSeekComplete called") ;}@ Override public void onPrepared (MediaPlayer player) {// This method is triggered when prepare is complete, here we play the video // first obtain the video width and height vWidth = player. getVideoWidth (); vHeight = player. getVideoHeight (); if (vWidth> currDisplay. getWidth () | vHeight> currDisplay. getHeight () {// if the video width or height exceeds the current screen size, scale float wRatio = (float) vWidth/(float) currDisplay. getWidth (); float hRatio = (float) vHeight/(float) currDisplay. getHeight (); // select a large one for scaling float ratio = Math. max (wRatio, hRatio); vWidth = (int) Math. ceil (float) vWidth/ratio); vHeight = (int) Math. ceil (float) vHeight/ratio); // sets the surfaceView layout parameter surfaceView. setLayoutParams (new LinearLayout. layoutParams (vWidth, vHeight); // start playing the video player. start () ;}@ Override public boolean onInfo (MediaPlayer player, int whatInfo, int extra) {// triggers the switch (whatInfo) when some specific information appears or warns) {case MediaPlayer. MEDIA_INFO_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_SERVER_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) {// trigger the Log when the MediaPlayer playback is complete. v ("Play Over:", "onComletion called"); this. finish () ;}</span>


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.