简体   繁体   中英

how do i make my android application play music from the phone's music player?

I've created an application, and now want it to be able to connect to the MediaPlayer on the phone, and play the songs from there, without leaving my application.

I want to add a toggle button that, when switched on, will start playing the playlists on the phone.

This is my code:

public class MainActivity extends Activity implements OnClickListener{
         ToggleButton tbMusic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tbMusic=(ToggleButton) findViewById(R.id.tbMusic);
        if(tbMusic.isChecked())
        {
            //here i want the command to be start playing the music
        }
        tbMusic.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.property, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v.getId()==R.id.tbMusic)
        {
            if(tbMusic.isChecked())
            {
                //here i want the command to be start playing the music
            }
            else
            {
                //here i want a command that will stop the media player.
            }
        }
    }
Private MediaPalyer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mp = MediaPlayer.create(this,R.raw.mymusic);

    tbMusic=(ToggleButton) findViewById(R.id.tbMusic);
    if(tbMusic.isChecked())
    {
       mp.start();
    }
    tbMusic.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.property, menu);
    return true;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId()==R.id.tbMusic)
    {
        if(tbMusic.isChecked())
        {
            mp.start();
        }
        else
        {
            mp.pause();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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