在音频播放器android中实现下一个按钮 [英] Implementing next button in audio player android

查看:98
本文介绍了在音频播放器android中实现下一个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在音频播放器应用中实现下一首歌曲按钮.我从教程中复制了一些代码,但没有用.下一首歌的按钮是 btnNext ,方法是 cde()它是代码.单击该按钮,但下一首歌曲不播放,当前歌曲继续播放.如何解决此问题?

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

推荐答案

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

上面的代码是您通过onClick方法获得的代码.

The above code is your code from the onClick method.

如您所见,您正在onClick内初始化currentPosition.

As you can see, you are initializing the currentPosition inside onClick.

因此,向您展示这意味着什么:

So to show you what this implies:

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

何时需要:

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

因此,在设置onCLickListener之前,您需要添加:

So, before setting the onCLickListener, you add:

currentPosition = 0;

currentPosition现在在类中声明,因此请确保将其添加.看起来应该像这样:

currentPosition is declared in the class now, so make sure you add it. It should look like this:

int currentPosition;

..other code

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

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

Remove int currentPosition = 0; from the onClick method.

我假设还有一个位置0.这是处理该问题的重构代码:

I assume there is a position 0 as well. 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();
}

以上代码正在解决您可能会遇到的另一个问题.歌曲0永远不会在第一轮播放.

The above code is addressing another issue you would be likely to meet. Song 0 would never play on the first round.

您要检查的另一件事(为方便起见,不给您提供代码)是如果没有歌曲,则不要播放或允许下一首歌曲.如果songs.size == 0,它将永远不会播放,而是将位置重复设置为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.

这篇关于在音频播放器android中实现下一个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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