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
MediaPlayer是Android中用于播放音频和视频的类。它提供了一系列方法和回调函数,可以控制媒体的播放、暂停、停止以及获取和更新播放进度等操作。 在使用MediaPlayer之前,需要先创建一个MediaPlayer对象,并设置数据源。有两种方式可以创建MediaPlayer对象,一种是直接使用new关键字创建一个实例,然后调用setDataSource()方法设置数据源;另一种是使用MediaPlayerUtil类进行封装,通过init()方法进行初始化,并设置回调函数监听媒体状态的变化。 使用MediaPlayer时,可以通过调用start()方法开始播放音频,通过onPrepared()回调函数监听音频加载完成的事件,在此方法中可以取消加载进度条并开始播放。通过onSeekUpdate()回调函数可以更新播放进度条的状态。onCompletion()回调函数可以监听音频播放完成的事件。如果发生错误,可以调用reset()方法重置UI状态,并返回true表示处理错误。 关于MediaPlayer的更多详细信息,可以参考MediaPlayer的官方文档。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Android 使用MediaPlayer播放音频详解](https://blog.youkuaiyun.com/baidu_38627723/article/details/120429916)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值