当我点击mediaplayer中的listview时,会播放多首歌曲

时间:2017-01-03 07:35:12

标签: android listview android-studio android-mediaplayer

您好我正在创建音乐播放器应用。

我遇到一个问题,当我点击listview时它会播放歌曲。

当我再一次点击列表视图时,歌曲就会一起播放。

上一首歌并没有停止。

我遵循了许多tuts和博客以及stackoverflow的答案,但没有任何工作。

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

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;
        }
    }


    }

这是我一起播放歌曲的音乐播放活动: -

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();

            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

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

使用单个MediaPlayer实例。

创建一个单例类,并从那里使用MediaPlayer。

或者您可以在ListView活动中将MediaPlayer设为公共静态。

public static MediaPlayer mp = new MediaPlayer();

now_playing活动

中使用此MediaPlayer

答案 1 :(得分:1)

我遇到了同样的问题并且修复了这样的问题。更改您的项目要求。

全局声明您的mediaPlayer实例

static MediaPlayer mediaPlayer = new MediaPlayer();

创建AudioManager和音量设置(注意:我使用Max Volume播放声音):

AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.FLAG_PLAY_SOUND);

然后将此代码放在点击

上的播放按钮上
        try {

            if (mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                mediaPlayer.release();
                mediaPlayer = null;
            }

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

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