当我在Mediaplayer中单击列表视图时,正在播放多首歌曲 [英] Multiple songs are playing when I click on listview in mediaplayer

查看:69
本文介绍了当我在Mediaplayer中单击列表视图时,正在播放多首歌曲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我正在创建音乐播放器应用.

Hello I am creating Music player app.

我有一个问题,当我单击列表视图时,它会播放歌曲.

I have a problem in that when I click on listview it plays song.

再次单击列表视图时,歌曲将一起播放.

When once again I clicked on listview then songs are playing together.

上一首歌曲不会停止

我关注了很多tut和博客以及stackoverflow的答案,但没有任何效果.

I followed many tuts and blogs and stackoverflow answers but nothing is worked.

这是我的活动,其中包含歌曲列表视图:-

Here is my Activity which contains songs list view :-

public class songlist extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

    private ListView lv_songlist;
    public Cursor cursor;

    private MediaCursorAdapter mediaAdapter = null;
    private String currentFile;

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

        lv_songlist = (ListView) findViewById(R.id.songlist);


        cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);

        if (null != cursor)
        {
            cursor.moveToFirst();

            mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);



            lv_songlist.setAdapter(mediaAdapter);
            lv_songlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    currentFile = (String) view.getTag();

                    Intent myIntent = new Intent(songlist.this,
                        now_playing.class);
                    myIntent.putExtra("song",""+currentFile);
                    myIntent.putExtra("cursor-position",cursor.getPosition());
                    startActivity(myIntent);
                }
            });
        }

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent myIntent = new Intent(songlist.this,
                    now_playing.class);
                myIntent.putExtra("song","");
                startActivity(myIntent);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) 
        {
            drawer.closeDrawer(GravityCompat.START);
        } 
        else 
        {
            super.onBackPressed();
        }
    }

        @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.songlist, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_camera)
        {
        } 
        else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }



    private class MediaCursorAdapter extends SimpleCursorAdapter {

        public MediaCursorAdapter(Context context, int layout, Cursor c) {
            super(context, layout, c,
                new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
                new int[]{R.id.displayname, R.id.title, R.id.duration});
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            TextView title = (TextView) view.findViewById(R.id.title);
            TextView name = (TextView) view.findViewById(R.id.displayname);
            TextView duration = (TextView) view.findViewById(R.id.duration);

            name.setText(cursor.getString(
                cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));

            title.setText(cursor.getString(
                cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));

            long durationInMs = Long.parseLong(cursor.getString(
                cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));

            Duration d = new Duration();

            String durationInMin = d.convertDuration(durationInMs);

            duration.setText("" + durationInMin);

            view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            LayoutInflater inflater = LayoutInflater.from(context);
            View v = inflater.inflate(R.layout.listitem, parent, false);

            bindView(v, context, cursor);

            return v;
        }
    }


    }

这是我的音乐演奏活动,可以一起播放歌曲:-

And This is my music playing activity which plays songs together :-

public class now_playing extends AppCompatActivity implements View.OnClickListener{

    private MediaPlayer mp = new MediaPlayer();
    private Cursor cursor;
    private RelativeLayout rl_album;
    private TextView Title_now_playing,duration_now_playing;
    private String Title,Duration,currentSong;
    private int cursorPosition;
    private ImageButton playPrev,playNext,seekFwd,seekBwd;

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


        setTitle("");
        cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        android.support.v7.app.ActionBar mActionBar = getSupportActionBar();



        LayoutInflater mInflater = LayoutInflater.from(this);

        View mCustomView = mInflater.inflate(R.layout.custom_layout_now_playing_for_action_bar, null);


        Title_now_playing = (TextView) mCustomView.findViewById(R.id.title_text);
        duration_now_playing = (TextView) findViewById(R.id.duration);

        playNext = (ImageButton) findViewById(R.id.playNext);

        rl_album = (RelativeLayout) findViewById(R.id.rl_album);
        Title_now_playing.setText(Title);

        mActionBar.setCustomView(mCustomView);
        mActionBar.setDisplayShowCustomEnabled(true);


        Intent in = getIntent();
        currentSong = in.getStringExtra("song");
        cursorPosition = in.getIntExtra("cursor-position",1);

            displayDetails();


        playNext.setOnClickListener(this);
    }



    void displayDetails(){
        mp.stop();
        mp.reset();
        if(!currentSong.equals(""))
        {
            cursor.move(cursorPosition+1);
            try {
                mp.setDataSource(currentSong);
                mp.prepare();
                mp.start();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Title = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME));
            int duration = cursor.getColumnIndex
                (MediaStore.Audio.Media.DURATION);

            long SongDuration = cursor.getLong(duration);
            com.example.davda.musicmain.Duration d = new Duration();
            Duration = d.convertDuration(SongDuration);
            duration_now_playing.setText(Duration);
            Title_now_playing.setText(Title);

            ContentResolver musicResolve = getContentResolver();
            Uri smusicUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
            Cursor musicCursorTogetAlbum =musicResolve.query(smusicUri,null         //should use where clause(_ID==albumid)
                ,null, null, null);



            musicCursorTogetAlbum.move(cursorPosition+1);        //i put only one song in my external storage to keep things simple;
        try{
            int x = musicCursorTogetAlbum.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
            String thisArt = musicCursorTogetAlbum.getString(x);


            Bitmap bm = BitmapFactory.decodeFile(thisArt);
            Drawable dr = new BitmapDrawable(getResources(), bm);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                rl_album.setBackground(dr);
            }
        }catch (RuntimeException re)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                rl_album.setBackgroundColor(Color.BLACK);
            }
        }
    }
}


public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.now_playing_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case android.R.id.home:
            Intent myIntent = new Intent(now_playing.this,
                    songlist.class);
            startActivity(myIntent);
            return true;

        case R.id.custom_equalizer:
            Toast.makeText(now_playing.this,"Custom Equalizer button pressed. Good broooooooooooooooooooooo...",Toast.LENGTH_LONG).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.playNext: {

                cursor.moveToNext();

                currentSong = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));

                displayDetails();

            }
        }
    }
}

推荐答案

因为您每次在活动中都创建MediaPlayer的新实例.

Because you are creating new Instance of MediaPlayer every-time in your activity.

使用MediaPlayer的一个实例.

Use a single Instance of MediaPlayer.

创建一个单例类,然后从那里使用MediaPlayer.

Create a singleton class and and use MediaPlayer from there.

或者您也可以在ListView活动中将MediaPlayer设为public static.

Or you can make MediaPlayer as public static in your ListView Activity.

public static MediaPlayer mp = new MediaPlayer();

并在 now_playing活动

这篇关于当我在Mediaplayer中单击列表视图时,正在播放多首歌曲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆