Recylerview:获取mediaplayer.setDataSource Android

时间:2018-09-18 04:21:37

标签: android android-recyclerview android-mediaplayer

我一直在致力于这个项目,以便在我们打开应用程序时自动在recyclerview中播放mp3文件。现在我面临的问题是一个例外。

这是我的MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static  final String URL = "http://myurl.com/mylanguage/a_displays.php";

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    private List<Radio> radioList;
     ProgressDialog progressDialog;
    long queueid,queueid1;
    private ApplicationPreferences applicationPreferences;
    DownloadManager dm;
            private MediaPlayer mediaplayer;
    int next = 0;


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

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        applicationPreferences = new ApplicationPreferences(this);

        radioList = new ArrayList<>();

        mediaplayer = new MediaPlayer();

        mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaplayer.start();
            }
        });
        adapter = new RadioAdapter(radioList,this);
        applicationPreferences.getCodeValue();
        final String codeValue = getIntent().getStringExtra("CODEINTENT");
        //Log.d("valueID",codeValue);
        int flag = getIntent().getIntExtra("chckDownload",0);

        if(flag == 1)
        {
            String path = getExternalFilesDir(DIRECTORY_DOWNLOADS)+ "/" +codeValue+ "/uploads/";
            Log.d("Files", "Path: " + path);
            File directory = new File(path);
            final File[] files = directory.listFiles();
           final String [] myAray = new String[files.length];

            Log.d("Files", "Size: "+ files.length);
            myAray[next] = getExternalFilesDir(DIRECTORY_DOWNLOADS) + "/" + codeValue + "/uploads/" + files[next].getName();
            Log.d("Files", "StringArray:" + myAray[next] + "index" + next);
            Log.d("Files", "FileName:" + files[next].getName());
            Radio rad = new Radio(0, files[next].getName());
            radioList.add(rad);
            do {

                try {

                        mediaplayer.setDataSource(this, Uri.parse(myAray[next]));
                    mediaplayer.prepareAsync();
                    mediaplayer.start();
                    Log.d("ValueOfi", String.valueOf(next));

                    mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mp.start();
                            next++;

                        }
                    });


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }while(next <= files.length);

            }


        else{
            datadummy(codeValue);

        }
        recyclerView.setAdapter(adapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void listFilesForFolder(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
                Radio rad = new Radio(0,fileEntry.getName());
                radioList.add(rad);

            }
        }
    }

    private void playmedia(String myAray[], String codeValue){
        try {

                Uri music_play = Uri.parse(getExternalFilesDir(DIRECTORY_DOWNLOADS) + "/" + codeValue + "/uploads/" + myAray[next]);
//                    MediaPlayer mp = MediaPlayer.create(this,music_play);
                mediaplayer.setDataSource(this, music_play);
                mediaplayer.prepareAsync();
                mediaplayer.start();
                next++;
                Log.d("ValueOfi", String.valueOf(next));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void datadummy(final String codeVal) {

        StringRequest stringRequest = new StringRequest(Request.Method.POST,URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response){
                        try {
                            JSONArray array = new JSONArray(response);

                            for (int i = 0; i < array.length(); i++) {
//

                                Log.d("MusicName", String.valueOf(array.getJSONObject(i).getString("audio_sound")));

                                final String music_uri = "http://myurl.in/mylanguage/" + array.getJSONObject(i).getString("audio_sound");

                                Uri uri = Uri.parse(music_uri);
                                applicationPreferences.getCodeValue();
                                dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                DownloadManager.Request request = new DownloadManager.Request(uri);

                                String.valueOf(request.setDestinationInExternalFilesDir(MainActivity.this,
                                        DIRECTORY_DOWNLOADS + "/"+codeVal,
                                        String.valueOf(array.getJSONObject(i).getString("audio_sound"))));
                                queueid = dm.enqueue(request);
                            }

                            BroadcastReceiver receiver = new BroadcastReceiver() {
                                @Override
                                public void onReceive(Context context, Intent intent) {
                                    String action = intent.getAction();
                                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

                                        DownloadManager.Query req_query = new DownloadManager.Query();
                                        req_query.setFilterById(queueid);

                                        Cursor c = dm.query(req_query);

                                        if (c.moveToFirst()) {
                                            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);

                                            if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                                                File folder = new File(getExternalFilesDir(DIRECTORY_DOWNLOADS)+ "/" +codeVal+ "/uploads/" );
                                                Log.d("asd", String.valueOf(folder));

                                                listFilesForFolder(folder);
                                                adapter.notifyDataSetChanged();
                                            }

                                        }

                                    }
                                }
                            };
                            registerReceiver(receiver,new IntentFilter((DownloadManager.ACTION_DOWNLOAD_COMPLETE)));




                            Log.d("-response",response);


                        }catch (JSONException e){
                            e.printStackTrace();
                            Log.d("Main", "JsonException: " + e);
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }

        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("album_code", codeVal);
                return params;
            }
        };

        RequestQueue requestqueue = Volley.newRequestQueue(this);
        requestqueue.add(stringRequest);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent intent = new Intent(MainActivity.this,HomeScreen.class);
                startActivity(intent);
                applicationPreferences.clearPreferences();
                return true;

            case R.id.action_refresh:
                // User chose the "Favorite" action, mark the current item
                // as a favorite...
                return true;

            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }

}

这是我的logcat:

  

E / Android运行时:致命异常:主要                                                                                        流程:com.teaminertia.user.radioapplication,PID:9625                                                                                        java.lang.RuntimeException:无法启动活动ComponentInfo {com.teaminertia.user.radioapplication / com.teaminertia.user.radioapplication.MainActivity}:java.lang.IllegalStateException                                                                                            在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)                                                                                            在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)                                                                                            在android.app.ActivityThread.-wrap14(ActivityThread.java)                                                                                            在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1642)                                                                                            在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                            在android.os.Looper.loop(Looper.java:154)                                                                                            在android.app.ActivityThread.main(ActivityThread.java:6776)                                                                                            在java.lang.reflect.Method.invoke(本机方法)                                                                                            在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1496)                                                                                            在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)                                                                                         造成原因:java.lang.IllegalStateException                                                                                            在android.media.MediaPlayer._setDataSource(本机方法)                                                                                            在android.media.MediaPlayer.setDataSource(MediaPlayer.java:1323)                                                                                            在android.media.MediaPlayer.setDataSource(MediaPlayer.java:1306)                                                                                            在android.media.MediaPlayer.setDataSource(MediaPlayer.java:1216)                                                                                            在android.media.MediaPlayer.setDataSource(MediaPlayer.java:1129)                                                                                            在android.media.MediaPlayer.setDataSource(MediaPlayer.java:1075)                                                                                            在android.media.MediaPlayer.setDataSource(MediaPlayer.java:1052)                                                                                            在com.teaminertia.user.radioapplication.MainActivity.onCreate(MainActivity.java:107)                                                                                            在android.app.Activity.performCreate(Activity.java:6955)                                                                                            在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)                                                                                            在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)                                                                                            在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)                                                                                            在android.app.ActivityThread.-wrap14(ActivityThread.java)                                                                                            在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1642)                                                                                            在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                            在android.os.Looper.loop(Looper.java:154)                                                                                            在android.app.ActivityThread.main(ActivityThread.java:6776)                                                                                            在java.lang.reflect.Method.invoke(本机方法)                                                                                            在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1496)                                                                                            com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

我的目标是同时播放mp3文件

1 个答案:

答案 0 :(得分:0)

setDataSource仅在MediaPlayer处于空闲状态时有效。在您的情况下,您得到IllegalStateException是因为您在setDataSource处于播放状态或未处于空闲状态时设置了MediaPlayer

mediaplayer.reset()方法将MediaPlayer重置为空闲状态(未初始化状态)

那么您就需要像这样再次对其进行初始化。

    mediaPlayer.setDataSource(your_data_source);
    mediaPlayer.prepare();
    mediaPlayer.start();

因此您只需在设置setDataSource之前重置媒体播放器

here是媒体播放器的状态图