简体   繁体   English

mediaplayer.create()和mediaplayer.prepareAsync()有什么区别?

[英]What is the difference between mediaplayer.create() and mediaplayer.prepareAsync()?

I have used the following code: 我使用了以下代码:

mp = MediaPlayer.create(this, Uri.parse("file://"+filePath));
mp.start(); 

This works fine. 这很好。 Then I wanted to play music from a folder 然后我想从文件夹播放音乐

mp.setDataSource(this, Uri.parse("file://"+filePath));
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });

Are there any performance differences between the two method? 两种方法之间是否存在性能差异?

The first approach ties up whatever thread you are on, long enough for MediaPlayer to read in the metadata of the media and prepare some buffers. 第一种方法束缚了您所处的线程,足够长的时间让MediaPlayer读取媒体的元数据并准备一些缓冲区。 If this is the main application thread, it means that your UI will be frozen while this is going on. 如果这是主要的应用程序线程,则意味着在此过程中您的UI将被冻结。

You can check MediaPlayer create() source code to see the difference: 您可以检查MediaPlayer create()源代码以查看区别:

 public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder,
        AudioAttributes audioAttributes, int audioSessionId) {

    try {
        MediaPlayer mp = new MediaPlayer();
        final AudioAttributes aa = audioAttributes != null ? audioAttributes :
            new AudioAttributes.Builder().build();
        mp.setAudioAttributes(aa);
        mp.setAudioSessionId(audioSessionId);
        mp.setDataSource(context, uri);
        if (holder != null) {
            mp.setDisplay(holder);
        }
        mp.prepare();
        return mp;
    } catch (IOException ex) {
        Log.d(TAG, "create failed:", ex);
        // fall through
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "create failed:", ex);
        // fall through
    } catch (SecurityException ex) {
        Log.d(TAG, "create failed:", ex);
        // fall through
    }

    return null;
}

Basically create() call is synchronous (it internally calls prepare() ) and prepareAsync() is asynchronous. 基本上create()调用是同步的(内部调用prepare() ), prepareAsync()是异步的。

Sure, create method inits object in main thread. 当然,在主线程中创建方法inits对象。 So code lines below it should wait for create. 因此,它下面的代码行应等待创建。

On the other hand, prepare asynchronous opens a new thread to init object then notify you to run next operations while main thread run other lines. 另一方面,prepare异步打开一个新线程来初始化对象,然后通知您运行下一个操作,而主线程运行其他行。

Edit: As @CommonWares mentioned in the comment, mp.create() is a convenient method of calling mp.setDataSoucer() + mp.prepare() at the same time 编辑:正如评论中提到的mp.create()mp.create()是同时调用mp.setDataSoucer() + mp.prepare()的便捷方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM