这是我的MainActivity代码。我只使用一项活动:
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button bPlay,bStop;
public static MediaPlayer mplayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bPlay=(Button)findViewById(R.id.button);
bStop=(Button)findViewById(R.id.button2);
bPlay.setOnClickListener(this);
bStop.setOnClickListener(this);
}
@Override
public void onClick(View v){
switch(v.getId()){
case R.id.button:
String path = "/sdcard/honey.mp3";
//bStop.setText(path);
// Uri myUri = Uri.parse("file:///storage/emulated/0/honey.mp3/");
//Uri myUri = Uri.parse("android.resource://com.example.shubhamchauhan.mediaplayer/"+R.raw.honey);
mplayer = new MediaPlayer();
mplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try{
mplayer.setDataSource(path);
}catch(IllegalArgumentException e){
Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
}catch(SecurityException e){
Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
}catch(IllegalStateException e){
Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
}catch(IOException e){
Toast.makeText(getApplicationContext(),"You set wrong uri start",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
try {
mplayer.prepare();
}catch(IllegalStateException e){
Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
}catch(IOException e){
Toast.makeText(getApplicationContext(),"You set wrong uri prepare",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
mplayer.start();
break;
case R.id.button2:
if(mplayer!=null && mplayer.isPlaying()){
mplayer.stop();
}
break;
}
}
}
如何解决?