MediaPlayer

介绍MediaPlayer的使用方法。

SDK Docs

下面是SDK Doc中的部分介绍。

Audio and Video Playback

Media can be played from anywhere: from a raw resource, from a file from the system, or from an available network (URL).

You can play back the audio data only to the standard output device; currently, that is the mobile device speaker or Bluetooth headset. You cannot play sound files in the conversation audio.

Playing from a Raw Resource

Perhaps the most common thing to want to do is play back media (notably sound) within your own applications. Doing this is easy:

Put the sound (or other media resource) file into the res/raw folder of your project, where the Eclipse plugin (or aapt) will find it and make it into a resource that can be referenced from your R class

Create an instance of MediaPlayer, referencing that resource using MediaPlayer.create, and then call start() on the instance:

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);    
mp.start();

To stop playback, call stop(). If you wish to later replay the media, then you must reset() and prepare() the MediaPlayer object before calling start() again. (create() calls prepare() the first time.)

To pause playback, call pause(). Resume playback from where you paused with start().

Playing from a File or Stream

You can play back media files from the filesystem or a web URL:

  1. Create an instance of the MediaPlayer using new
  2. Call setDataSource() with a String containing the path (local filesystem or URL) to the file you want to play
  3. First prepare() then start() on the instance:

    MediaPlayer mp = new MediaPlayer();
    mp.setDataSource(PATH_TO_FILE);
    mp.prepare();
    mp.start();

stop() and pause() work the same as discussed above.

Note: It is possible that mp could be null, so good code should null check after the new. Also, IllegalArgumentException and IOException either need to be caught or passed on when using setDataSource(), since the file you are referencing may not exist.

Note: If you’re passing a URL to an online media file, the file must be capable of progressive download.

示例

功能

把mp3放在res\raw目录下面,然后Start开始播放,Stop停止播放。

效果

UI

my_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/stop" />

</LinearLayout>

string

<string name="start">Start</string>
<string name="stop">Stop</string>

代码

略掉自动生成的代码。

public class MainActivity extends Activity {
    private MediaPlayer mp = null;
    private Button start = null;
    private Button stop = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);

        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);

        stop.setEnabled(false);

        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.prepare();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                mp.start();
                start.setEnabled(false);
                stop.setEnabled(true);
            }
        });

        stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
                start.setEnabled(true);
                stop.setEnabled(false);
            }
        });

        mp = MediaPlayer.create(this, R.raw.test);
        mp.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                start.setEnabled(true);
                stop.setEnabled(false);
            }
        });
    }

媒体文件的位置

assets目录

媒体文件除了可以放在res下面之外,还可以放在assets目录下。前者会在R.java中生成id,但后者不会。后者需要用文件名和路径来引用。

前面例子中初始化mp对象的代码:

mp = MediaPlayer.create(this, R.raw.test);

可以换为:

mp = new MediaPlayer();
mp.setOnCompletionListener(new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        start.setEnabled(true);
        stop.setEnabled(false);
    }
});

AssetFileDescriptor fd = null;
try {
    fd = getAssets().openFd("test.mp3");
    mp.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
    fd.close();
} catch (IOException e) {
    e.printStackTrace();
    finish();
}

res下用FileDespcriptor

对于res下面的媒体文件,也可以用上述方法取得FileDescriptor对象。如对应的调用改成下面这句:

fd = getResources().openRawResourceFd(R.raw.test);

动态切换媒体文件

通过调用setDataSource()可以改变媒体文件。

题外话

关于assets目录和raw目录的差异,则是MediaPlayer之外的一个话题,本文不展开讨论。

API调用顺序

MediaPlayer的各个方法在调用时,必须注意调用顺序。否则,可能原因出现异常而崩溃,或者媒体刚开始播放就显示结束。
比如,下面的setAudioStreamType()必须在prepare()之前调用。

Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();

为此,可以多查阅MediaPlayer的文档。比如对于setAudioStreamType就有如下说明:

Successful invoke of this method does not change the state. In order for the target audio stream type to become effective, this method must be called before prepare() or prepareAsync().

参考资料

  • 使用方法:docs/guide/topics/media/mediaplayer.html
  • 状态图、API调用顺序:docs/reference/android/media/MediaPlayer.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值