如何使用MediaPlayer播放歌曲

时间:2015-10-10 14:40:33

标签: java android

我正在尝试制作一种音乐播放器,看起来很顺利,但现在我必须创建一些东西来保持音乐播放即使应用程序关闭,我该怎么做?也许有服务?我该怎么办?如果它有用,那就是代码:

MainActivity.java

package me.eskilop.yamp;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

public class MainActivity extends AppCompatActivity implements ControlsActivityFragment.ControlsListener{

    ListView list;
    String[] items;
    ArrayList<File> canzoni = PlayerActivity.canzoni;
    int p = PlayerActivity.position;
    ControlsActivityFragment caf;

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

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setStatusBarColor(Color.parseColor("#0097A7"));
            window.setNavigationBarColor(Color.parseColor("#0097A7"));
            android.support.v7.app.ActionBar ab = getSupportActionBar();
            ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00BCD4")));
        }
        else
        {
            android.support.v7.app.ActionBar ab = getSupportActionBar();
            ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00BCD4")));
        }

        list = (ListView)findViewById(R.id.list);

        final ArrayList<File> canzoni = findSongs(Environment.getExternalStorageDirectory());

        items = new String[ canzoni.size() ];

        for (int i = 0; i < canzoni.size(); i++)
        {
            items[i] = canzoni.get(i).getName().toString().replace(".mp3", "").replace(".wav", "");
        }

        ArrayAdapter<String> songadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.songlayout, R.id.textView, items);
        list.setAdapter(songadapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (PlayerActivity.mediaPlayer != null)
                {
                    if (PlayerActivity.mediaPlayer.isPlaying())
                    {
                        PlayerActivity.mediaPlayer.release();
                        startActivity(new Intent(getApplicationContext(), PlayerActivity.class).putExtra("pos", position).putExtra("songlist", canzoni));
                    }
                    else
                    {
                        if (PlayerActivity.paused == true){
                            caf.pp.setImageResource(R.drawable.play);
                        }
                        else
                        {
                            startActivity(new Intent(getApplicationContext(), PlayerActivity.class).putExtra("pos", position).putExtra("songlist", canzoni));
                            caf.pp.setImageResource(R.drawable.pause);
                        }

                    }
                }
                else
                {
                    startActivity(new Intent(getApplicationContext(), PlayerActivity.class).putExtra("pos", position).putExtra("songlist", canzoni));
                }
            }
        });
    }

    @Override
    public void handleclick(View v)
    {

        caf = (ControlsActivityFragment) getSupportFragmentManager().findFragmentById(R.id.controls_fragment);

        switch (v.getId())
        {
            case R.id.ic_pp:
                if(PlayerActivity.mediaPlayer != null)
                {
                    if(PlayerActivity.mediaPlayer.isPlaying())
                    {
                        caf.pp.setImageResource(R.drawable.play);
                        PlayerActivity.mediaPlayer.pause();
                    }
                    else
                    {
                        caf.pp.setImageResource(R.drawable.pause);
                        PlayerActivity.mediaPlayer.start();
                    }
                }
                break;
            case R.id.ic_next:
                caf.pp.setImageResource(R.drawable.pause);
                PlayerActivity.nextSong(getApplicationContext());
                ControlsActivityFragment.sname.setText(PlayerActivity.canzoni.get(PlayerActivity.position).getName());
                break;
            case R.id.ic_prev:
                caf.pp.setImageResource(R.drawable.pause);
                PlayerActivity.previousSong(getApplicationContext());
                ControlsActivityFragment.sname.setText(PlayerActivity.canzoni.get(PlayerActivity.position).getName());
        }
    }

    public ArrayList<File> findSongs(File root)
    {
        ArrayList<File> s = new ArrayList<File>();
        File [] files = root.listFiles();
        for (File singleFile : files)
        {
            if (singleFile.isDirectory() && !singleFile.isHidden())
            {
                s.addAll(findSongs(singleFile));
            }
            else
            {
                if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav"))
                {
                    s.add(singleFile);
                }
            }
        }
        return s;
    }

}

PlayerActivity.java

package me.eskilop.yamp;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;

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

public class PlayerActivity extends AppCompatActivity implements View.OnClickListener{

    static ArrayList<File> canzoni;
    static MediaPlayer mediaPlayer;
    static int position;
    static boolean paused;
    ImageView pp;
    static Uri u;

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

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setStatusBarColor(Color.parseColor("#0097A7"));
            window.setNavigationBarColor(Color.parseColor("#0097A7"));
            android.support.v7.app.ActionBar ab = getSupportActionBar();
            ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00BCD4")));
        }
        else
        {
            android.support.v7.app.ActionBar ab = getSupportActionBar();
            ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00BCD4")));
        }

        ImageView previous = (ImageView)findViewById(R.id.previous);
        previous.setOnClickListener(this);
        pp = (ImageView)findViewById(R.id.ic_pp);
        pp.setOnClickListener(this);
        ImageView next = (ImageView)findViewById(R.id.next);
        next.setOnClickListener(this);

        Intent i = getIntent();
        Bundle b = i.getExtras();

        canzoni = (ArrayList) b.getParcelableArrayList("songlist");
        position = b.getInt("pos", 0);

        u = Uri.parse(canzoni.get(position).toString());
        mediaPlayer = mediaPlayer.create(getApplicationContext(), u);
        ControlsActivityFragment.sname.setText(canzoni.get(position).getName());
        mediaPlayer.start();

    }

    @Override
    public void onClick(View v)
    {
        int id = v.getId();
        switch (id)
        {
            case R.id.previous:
                previousSong(getApplicationContext());
                break;
            case R.id.ic_pp:
                if(mediaPlayer.isPlaying())
                {
                    pp.setImageResource(R.drawable.play);
                    mediaPlayer.pause();
                }
                else
                {
                    pp.setImageResource(R.drawable.pause);
                    mediaPlayer.start();
                    paused = true;
                }
                break;
            case R.id.next:
               nextSong(getApplicationContext());
                break;
        }
    }

    static void previousSong(Context context)
    {
        mediaPlayer.stop();
        mediaPlayer.release();
        position = (position-1<0)? canzoni.size() : position-1;
        u = Uri.parse(canzoni.get((position)%canzoni.size()).toString());
        mediaPlayer = mediaPlayer.create(context, u);
        mediaPlayer.start();
    }

    static void nextSong(Context context)
    {
        mediaPlayer.stop();
        mediaPlayer.release();
        position = (position+1 > canzoni.size()) ? 0 : position+1;
        u = Uri.parse(canzoni.get(position).toString());
        mediaPlayer = mediaPlayer.create(context, u);
        mediaPlayer.start();
    }

}

ControlsActivityFragment.java

package me.eskilop.yamp;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by root on 22/09/15.
 */
public class ControlsActivityFragment extends Fragment
{

    ControlsListener listener;

    ImageView prev;
    ImageView pp;
    ImageView next;
    static TextView sname;

    public interface ControlsListener
    {
        void handleclick(View v);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try
        {
            listener = (ControlsListener) activity;
        }
        catch (ClassCastException a)
        {
            a.printStackTrace();
        }
    }

    View.OnClickListener cl = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            listener.handleclick(v);
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.controls_activity_fragment, container, false);

        sname = (TextView) view.findViewById(R.id.songname);

        prev = (ImageView) view.findViewById(R.id.ic_prev);
        prev.setOnClickListener(cl);

        pp = (ImageView) view.findViewById(R.id.ic_pp);
        pp.setOnClickListener(cl);

        next = (ImageView) view.findViewById(R.id.ic_next);
        next.setOnClickListener(cl);

        return view;
    }
}

提前致谢:)

0 个答案:

没有答案