简体   繁体   English

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

[英]Implementing next button in audio player android

I have been trying to implement next song button in my audio player app. 我一直在尝试在音频播放器应用中实现下一首歌曲按钮。 I copied some code from a tutorial but its not working.The button for next song is btnNext and the method is cde(), its the last method in the code. 我从教程中复制了一些代码,但是它不起作用。下一首歌的按钮是btnNext ,方法是cde(), 这是代码中的最后一个方法。 The button gets clicked but next song is not played, current song keeps playing.How do I fix this ? 单击该按钮但不播放下一首歌曲,当前歌曲继续播放。如何解决此问题?

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

Add this in onCreate method: 在onCreate方法中添加以下内容:

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

And change next button listener to 并将下一个按钮侦听器更改为

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();
                }
            });
    int currentPosition = 0;
    if (++currentPosition >= songs.size()) {
        currentPosition = 0;
    } else
            try {
                playSong(path + songs.get(currentPosition));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
    }

The above code is your code from the onClick method. 上面的代码是onClick方法中的代码。

As you can see, you are initializing the currentPosition inside onClick. 如您所见,您正在onClick中初始化currentPosition。

So to show you what this implies: 因此,向您展示这意味着什么:

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

When you want: 当你想要的时候:

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

So, before setting the onCLickListener, you add: 因此,在设置onCLickListener之前,您需要添加:

currentPosition = 0;

currentPosition is declared in the class now, so make sure you add it. 现在在类中声明了currentPosition,因此请确保添加它。 It should look like this: 它看起来应该像这样:

int currentPosition;

..other code

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

Remove int currentPosition = 0; 删除int currentPosition = 0; from the onClick method. 从onClick方法。

I assume there is a position 0 as well. 我假设位置也是0。 Here is the refactored code that would handle that: 这是处理此问题的重构代码:

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

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

The above code is addressing another issue you would be likely to meet. 上面的代码解决了您可能会遇到的另一个问题。 Song 0 would never play on the first round. 歌曲0不会在第一轮播放。

Another thing you want to check for (not giving you the code for it as it is easy) is to not play or allow next song if there are no songs . 您要检查的另一件事(为方便起见,不给您提供代码)是,如果没有歌曲,则不要播放或允许下一首歌曲 If songs.size == 0 it would never play but set the position to 0 over and over. 如果songs.size == 0,它将永远不会播放,而是将位置songs.size设置为0。

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

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