The import android. App. The Activity;
The import android. Media. MediaPlayer;
The import android. OS. Bundle;
The import android. OS. The Environment;
The import android. View. The Menu;
The import android. View. MenuItem;
The import android. View. The view;
The import android. View. The view. An OnClickListener;
The import android. Widget. *;
Public class MainActivity extends the Activity implements an OnClickListener {
Private Button play;
Private Button pause;
Private Button stop;
Private MediaPlayer MediaPlayer=new MediaPlayer ();
@ Override
Protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Play=(Button) the findViewById (R.i d.p lay);
Pause=(Button) the findViewById (R.i d.p ause);
Stop=(Button) the findViewById (R.i d.s top);
InitMediaPlayer ();//initialize the MediaPlayer
Play. SetOnClickListener (this);
Pause. SetOnClickListener (this);
Stop. SetOnClickListener (this);
}
Private void initMediaPlayer () {
Try {
The File File=new File (Environment. External.getexternalstoragedirectory (), "music. Mp3");
MediaPlayer. SetDataSource (file. GetPath ());//the path of the specified audio file
MediaPlayer. Prepare ();//let the MediaPlayer into the ready state
} the catch (Exception e) {
e.printStackTrace();
}
}
@ Override
Public void onClick (View v) {
//TODO Auto - generated method stub
The switch (v.g etId ()) {
Case R.i d.p lay:
if(! MediaPlayer. IsPlaying ()) {
MediaPlayer. Start ();//start playing
}
break;
Case R.i d.p ause:
{if (mediaPlayer. IsPlaying ())
MediaPlayer. Pause ();/play/pause
}
break;
Case R.i d.s top:
{if (mediaPlayer. IsPlaying ())
MediaPlayer. Reset ();//stop play
InitMediaPlayer ();
}
break;
Default:
break;
}
}
@ Override
Protected void onDestroy () {
super.onDestroy();
If (mediaPlayer!=null) {
MediaPlayer. Stop ();
MediaPlayer. Release ();
}
}
}
CodePudding user response:
Must realize onPreparedListener inside the callback function to carry on the mediaplayer. Ready, start () resourcesIn addition to ensure the SDCARD to read and write permissions,
CodePudding user response:
Discovery is SDCARD permissions not write, prepare no problem,,,, thanks for the great god answeredCodePudding user response:
SDCARD permissions has written, but will still appear this error, what is the reason, a great god genuflect is begged