在音频播放器android中实现下一个按钮

时间:2017-07-22 10:28:10

标签: java android button onclick audio-player

我一直在尝试在我的音频播放器应用中实现下一首歌曲按钮。我从教程中复制了一些代码,但它不起作用。下一首歌的按钮是 btnNext ,方法是 cde(), 是它的最后一个方法代码。按钮被点击但下一首歌没有播放,当前的歌曲一直在播放。我该怎么解决这个问题?

package com.example.dell_1.myapp3;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.R.attr.path;

public class PlayListActivity extends Activity {

    private String[] mAudioPath;
    private MediaPlayer mMediaPlayer;
    private String[] mMusicList;
    int currentPosition = 0;
    private List<String> songs = new ArrayList<>();

    MediaMetadataRetriever metaRetriver;
    byte[] art;
    ImageView album_art;
    TextView album;
    TextView artist;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_list);

        mMediaPlayer = new MediaPlayer();
        ListView mListView = (ListView) findViewById(R.id.list);

        mMusicList = getAudioList();

        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, mMusicList);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                    long arg3) {

                try {
                    playSong(mAudioPath[arg2]);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private String[] getAudioList() {
        final Cursor mCursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
                "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");

        int count = mCursor.getCount();

        String[] songs = new String[count];
        mAudioPath = new String[count];
        int i = 0;
        if (mCursor.moveToFirst()) {
            do {
                songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                i++;
            } while (mCursor.moveToNext());
        }

        mCursor.close();

        return songs;
    }


    private void playSong(String path) throws IllegalArgumentException,
            IllegalStateException, IOException {

        setContentView(R.layout.activity_android_building_music_player);
        Log.d("ringtone", "playSong :: " + path);

        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        acv(path);
        abc();
        cde();
    }

    public void acv(String path) {
        getInit();

        metaRetriver = new MediaMetadataRetriever();
        metaRetriver.setDataSource(path);
        try {
            art = metaRetriver.getEmbeddedPicture();
            Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
            album_art.setImageBitmap(songImage);
            album.setText(metaRetriver
                    .extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
            artist.setText(metaRetriver
                    .extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
        } catch (Exception e) {
            album_art.setBackgroundColor(Color.GRAY);
            album.setText("Unknown Album");
            artist.setText("Unknown Artist");
        }

    }

    public void getInit() {
        album_art = (ImageView) findViewById(R.id.coverart1);
        album = (TextView) findViewById(R.id.Album);
        artist = (TextView) findViewById(R.id.artist_name);
    }


    public void abc() {
        ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
        btnPlay1.setBackgroundColor(Color.TRANSPARENT);
        btnPlay1.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                        if (mMediaPlayer.isPlaying()) {
                            mMediaPlayer.pause();
                        } else {
                            mMediaPlayer.start();
                        }

                    }
                });
    }




 public void cde() {
    ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);  //this is the button for playing next song.
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            try {
                        currentPosition=currentPosition+1;
                    playSong(path + songs.get(currentPosition));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
}
}

2 个答案:

答案 0 :(得分:0)

在onCreate方法中添加:

Bundle bundle = getIntent().getExtras();
position = bundle.getInt("position");

将下一个按钮监听器更改为

btnNext.setOnClickListener(new View.OnClickListener()    //this is the button                                          

                @Override
                public void onClick(View arg0) {
                   if (mMediaPlayer!= null && mMediaPlayer.isPlaying()) {
                     mMediaPlayer.stop();
                   }
                   uri = Uri.parse(mAudioPath[position + 1]);
                   mMediaPlayer.setDataSource(getApplicationContext(), uri);
                   mMediaPlayer.prepare();              
                   mMediaPlayer.start();
                }
            });

答案 1 :(得分:0)

    int currentPosition = 0;
    if (++currentPosition >= songs.size()) {
        currentPosition = 0;
    } else
            try {
                playSong(path + songs.get(currentPosition));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
    }

上面的代码是来自onClick方法的代码。

如您所见,您正在onClick中初始化currentPosition。

所以要告诉你这意味着什么:

onClick -> position = 0 -> position++ (position = 1) -> playSong(songUri)

何时需要:

onClick -> position++ -> playSong(songUri)

因此,在设置onCLickListener之前,请添加:

currentPosition = 0;

currentPosition现在在类中声明,因此请确保添加它。它应该是这样的:

int currentPosition;

..other code

public void cde(){
    ..code here
    currentPosition = 0;
   ... set onClickListener
}

从onClick方法中删除int currentPosition = 0;

我假设也有一个位置0。以下是处理该代码的重构代码:

try {
    playSong(path + songs.get(currentPosition));

    if (++currentPosition >= songs.size()) {
        currentPosition = 0;
    } 
} catch (IOException ex) {
    ex.printStackTrace();
}

上述代码正在解决您可能会遇到的另一个问题。歌曲0永远不会在第一轮上演。

如果没有歌曲,你想要检查的另一件事(不给你代码就好了)就是不播放或允许下一首歌。如果songs.size == 0,它将永远不会播放,但会将位置反复设置为0。