Android multimedia technology-MediaPlayer for audio and video playback

Source: Internet
Author: User

Hello, good evening, everyone finally got together again. In the past few days, I have been busy with a small project called encrypted notepad. Although it has not been improved yet, but I really miss you, so I 'd like to share with you the next new knowledge!

Let's talk about Android multimedia in this article today. I think it must be something that everyone is very interested in. Isn't it too impatient? Let's get started quickly!


I. Multimedia basics of Android

1. Basic Categories: There are two basic categories used to play audio and video in the Android framework;

1) MediaPlayer: provides all the APIS required for playing audio and video in Android;

2) AudioManager: used to manage audio and video resources and audio output devices;


2. Here we will detail the MediaPlayer knowledge:

1) MediaPlayer object lifecycle:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1021102c8-0.gif "title =" 201211221743465704.gif"/>

2) common methods:

Method: create (Context context, Uri uri) method: create (Context context, Uri uri)
Explanation: The static method creates a multimedia player through Uri.

Method: create (Context context, int resid)
Explanation: The static method creates a multimedia player using the resource ID.

Method: create (Context context, Uri uri, SurfaceHolder holder)
Explanation: The static method creates a multimedia player through Uri and the specified SurfaceHolder abstract class.

Method: getCurrentPosition ()
Explanation: Int is returned to obtain the current playback position.

Method: getDuration ()
Explanation: Int is returned to obtain the file time.

Method: getVideoHeight ()
Explanation: Int is returned to get the video height.

Method: getVideoWidth ()
Explanation: Int is returned to obtain the video width.

Method: isLooping ()
Explanation: boolean is returned, indicating whether to play cyclically.

Method: isPlaying ()
Explanation: boolean is returned, indicating whether the video is being played.

Method: pause ()
Explanation: no return value. Pause.

Method: prepare ()
Explanation: no return value. Prepare for synchronization.

Method: prepareAsync ()
Explanation: no return value. Prepare asynchronous

Method: release ()
Explanation: no return value. Release the MediaPlayer object.

Method: reset ()
Explanation: no return value. Reset the MediaPlayer object.

Method: seekTo (int msec)
Explanation: there is no return value. It specifies the playback position in milliseconds)

Method: setAudioStreamType (int streamtype)
Explanation: no return value indicates the streaming media type.

Method: setDataSource (String path)
Explanation: no return value. Set the multimedia data source to the path]

Method: setDataSource (FileDescriptor fd, long offset, long length)
Explanation: no return value. Set the multimedia data source according to FileDescriptor]

Method: setDataSource (FileDescriptor fd)
Explanation: no return value. Set the multimedia data source according to FileDescriptor]

Method: setDataSource (Context context, Uri uri)
Explanation: no return value. Set the multimedia data source to Uri]

Method: setDisplay (SurfaceHolder sh)
Explanation: no return value. Set SurfaceHolder to display multimedia.

Method: setLooping (boolean looping)
Explanation: no return value indicates whether to enable loop playback.

Event: setOnBufferingUpdateListener (MediaPlayer. OnBufferingUpdateListener listener)
Explanation: listening events and network streaming media buffer listening

Event: setOnCompletionListener (MediaPlayer. OnCompletionListener listener)
Explanation: Listener event, network Streaming Media Playback End listener

Event: setOnErrorListener (MediaPlayer. OnErrorListener listener)
Explanation: listens to events and sets the error message listener.

Event: setOnVideoSizeChangedListener (MediaPlayer. OnVideoSizeChangedListener listener)
Explanation: monitoring events and video size monitoring

Method: setScreenOnWhilePlaying (boolean screenOn)
Explanation: no return value. Set whether to use SurfaceHolder for display.

Method: setVolume (float leftVolume, float rightVolume)
Explanation: no return value. Set the volume.

Method: start ()
Explanation: no return value. start playing.

Method: stop ()
Explanation: no return value. Stop playing.


Ii. Audio Playback

In fact, in addition to this category, there is also a music playing class that is SoundPool. These two classes have different analyses for your understanding.

1. MediaPlayer:

This type of file is suitable for playing large files. Such files should be stored on the SD card, rather than in resource files. In addition, this type of file can only play one audio file at a time.

The usage is as follows:

(1) play from the resource file

MediaPlayer   player  =   new MediaPlayer.create(this,R.raw.test);              player.start();

(2) playback from the file system

MediaPlayer   player  =   new MediaPlayer();             String  path   =  "/sdcard/test.mp3";              player.setDataSource(path);              player.prepare();              player.start();

(3) playing from the network

(1) URI:

String path = "http ://**************. mp3 "; // here, the network address of a song is Uri uri = Uri. parse (path); MediaPlayer player = new MediaPlayer. create (this, uri); player. start ();

(2) set the Data source:

MediaPlayer player = new MediaPlayer. create (); String path = "http ://**************. mp3 "; // here, the network address of a song is the player. setDataSource (path); player. prepare (); player. start ();

2. SoundPool:

This type of feature is low-latency playback. It is suitable for playing real-time audio and playing multiple sounds at the same time, such as the explosion of bombs in the game and other petty source files, this type of audio is suitable for storing it in the resource folder res/raw and making it an APK file together with the program.

The usage is as follows:

SoundPool soundPool = new SoundPool (4, AudioManager. STREAM_MUSIC, 100); HashMap <Integer, Integer> soundPoolMap = new HashMap <Integer, Integer> (); soundPoolMap. put (1, soundPool. load (this, R. raw. dingdong1, 1); soundPoolMap. put (2, soundPool. load (this, R. raw. dingdong2, 2); public void playSound (int sound, int loop) {AudioManager mgr = (AudioManager) this. getSystemService (Context. AUDIO_SERVICE); float streamVolumeCurrent = mgr. getStreamVolume (AudioManager. STREAM_MUSIC); float streamVolumeMax = mgr. getStreamMaxVolume (AudioManager. STREAM_MUSIC); float volume = streamVolumeCurrent/streamVolumeMax; soundPool. play (soundPoolMap. get (sound), volume, volume, 1, loop, 1f); // parameters: 1. Set the value in Map to 2. Current Volume 3. Maximum Volume 4. Priority 5. Number of replays 6. playback speed} this. playSound (1, 0 );


Iii. Video Playback

1. Use the VideoView control:

1) MainActivity. java

package com.example.l0905_videoview;import java.io.File;import android.app.Activity;import android.net.Uri;import android.os.Bundle;import android.widget.VideoView;public class MainActivity extends Activity {    private VideoView vv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        vv=(VideoView) findViewById(R.id.videoView1);        vv.setVideoURI(Uri.fromFile(new File("D:\\english.mp4")));        vv.start();    }}

2) activitymain. xml

<VideoView    android:id="@+id/videoView1"    android:layout_width="match_parent"    android:layout_height="wrap_content" />

2. SurfaceView + MediaPlayer

1) MainActivity. java

package com.example.l0905_videoplayer;import java.io.File;import java.io.IOException;import android.app.Activity;import android.media.MediaPlayer;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.view.SurfaceHolder;import android.view.SurfaceView;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener{    private Button start,pause,set,stop;    private SurfaceView sv;    private MediaPlayer mp;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sv=(SurfaceView) findViewById(R.id.surfaceView1);        start=(Button) findViewById(R.id.button1);        pause=(Button) findViewById(R.id.button2);        set=(Button) findViewById(R.id.button3);        stop=(Button) findViewById(R.id.button4);        start.setOnClickListener(this);        pause.setOnClickListener(this);        set.setOnClickListener(this);        stop.setOnClickListener(this);    }    public void play(){        sv.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);        try {            mp.setDataSource(this, Uri.fromFile(new File(/*Environment.getExternalStorageDirectory().getAbsoluteFile()+*/"d:/english.mp4")));            mp.setDisplay(sv.getHolder());            mp.prepare();            mp.start();        } catch (IllegalArgumentException e) {            e.printStackTrace();        } catch (SecurityException e) {            e.printStackTrace();        } catch (IllegalStateException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    public void getPosition(){        if(mp.isPlaying()){            int timeAll=mp.getDuration();            System.out.println(timeAll);            int time=mp.getCurrentPosition();            System.out.println(time);        }    }    @Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.button1:            play();            getPosition();            break;        case R.id.button2:            if(mp.isPlaying()){                mp.pause();            }else{                mp.start();            }            getPosition();            break;        case R.id.button3:            mp.seekTo(60000);            getPosition();            break;        case R.id.button4:            mp.stop();            getPosition();            break;        }    }}

(2) xml

<LinearLayout xmlns: android =" http://schemas.android.com/apk/res/android "Xmlns: tools =" http://schemas.android.com/tools "Android: layout_width =" match_parent "android: layout_height =" match_parent "android: orientation =" vertical "tools: context = ". mainActivity "> <SurfaceView android: id =" @ + id/surfaceView1 "android: layout_width =" match_parent "android: layout_height =" wrap_content "android: layout_weight = "1"/> <LinearLayout android: layout_width = "match_parent" android: layout_height = "wrap_content" android: orientation = "horizontal"> <Button android: id = "@ + id/button1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_weight = "1" android: text = "start"/> <Button android: id = "@ + id/button2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_weight = "1" android: text = "pause"/> <Button android: id = "@ + id/button3" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_weight = "1" android: text = "specified"/> <Button android: id = "@ + id/button4" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_weight = "1" android: text = "stop"/> </LinearLayout>


This article is from the MySpace blog, please be sure to keep this source http://wangzhaoli.blog.51cto.com/7607113/1290206

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.