To start off, playing and stopping music works fine. I've already searched SX, and have tried some of the solutions listed for this issue, but they haven't resolved my issue.
I have a "Replay Music" button, that is supposed to restart an .mp3 file from the beginning. I've got the necessary code in place (like reset(), prepare(), etc, in order for the media player to replay the music, but when the button is pushed, nothing happens.
I have all the OnClickListeners and other necessary things setup, it is just this one issue.
Below is the complete code for my "Replay Music" method. Any help will be gratefully received.
Just a thought: Perhaps it is something to do with the placement of the mediaPlayer.start() method call?
public void replaySoundButtonListener() {
Button testButton = (Button) findViewById(R.id.replayMusicButton);
testButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource("sdcard/InsomniMusic/insomnimix.mp3");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
});
}
You only need to prepare and set the data source of a mediaplayer once. When you call reset the mediaplayer has to be reinitialised completely (set datasource again and call prepare). If you would like to reset the mediaplayer to the start of the song I guess you could use
mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
#Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
If the song has already ended (or stopped otherwise), only mediaPlayer.start() will suffice (but I guess in your case you can never be sure of that).
More information on the start function here
I made a functions to start() stop() reset() and pause() in another Class
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer extends MediaPlayer {
private MediaPlayer mPlayer;
public void stop()
{
if(mPlayer!=null)
{
mPlayer.release();
mPlayer=null;
}
}
public void pause()
{
if(mPlayer.isPlaying()) {
mPlayer.pause();
}
else
{
mPlayer.start();
}
}
public void reset(Context c)
{
stop();
mPlayer=MediaPlayer.create(c, R.raw.one_small_step); //uzimamo .create(context,..) jer uzimamo iz res/raw lokalne datoteke
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stop();
}
});
mPlayer.start();
}
public void play(Context c)
{
stop();
mPlayer=MediaPlayer.create(c, R.raw.one_small_step);
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stop();
}
});
mPlayer.start();
}
}
//Here is my fragment
private Button mPlayButton;
private Button mStopButton;
private Button mPauseButton;
private Button mResetButton;
private AudioPlayer mPlayer=new AudioPlayer();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=getActivity().getLayoutInflater().inflate(R.layout.fragment_hello_moon, container);
mPlayButton=(Button)v.findViewById(R.id.hellomoon_playButton);
mPlayButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.play(getActivity());
}
});
mStopButton=(Button)v.findViewById(R.id.hellomoon_stopButton);
mStopButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.stop();
}
});
mPauseButton=(Button)v.findViewById(R.id.hellomoon_pauseButton);
mPauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.pause();
}
});
mResetButton=(Button)v.findViewById(R.id.hellomoon_resetButton);
mResetButton.setOnClickListener(new OnClickListener(
) {
#Override
public void onClick(View v) {
mPlayer.reset(getActivity());
}
});
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
mPlayer.stop(); //Nakon sto je fragment unisten MediaPlayer nastavlja radit jer je na drugacijem Threadu pa treba pozvati Stop();
}
Related
I have an app with one button for play/stop music . when I run the app , music stops in start up of that . But I want when I run the app that music plays automatically and if I click the button , music stops . I searched the site but I cant find the answer .Please help me my friends.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
You can follow this:
if (mp == null) {
mp = MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
}
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
you can use toggle button like below
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
Call go() method in your activity oncreate method.
Its play automatically on activity start when you button clicked its again call the same method so the condition is palying so its stopped.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
go();
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
I am new to Android and in my app I am working with MediaPlayer.
When I first tap the start button, the song plays, but when I tap the stop button and then I tap on the start button again, the song does not start playing again. Here's what I have so far:
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
final MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
}
});
}
}
Try this :
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
}
});
just check like this way
if(mdpl.isPlaying()){
mdpl.pause();
} else {
mdpl.start();
}
You can not call start, it media player in on stop state. Take a look on the state diagram of media player MediaPlayer state diagram.
When you call stop, you have to call release(), and with start you get a new media player, or just call reset.
try this
public void onStopBtnClick(View view) {
if (mAudioHelper != null) {
mAudioHelper.stop();
displayMessage("Stopping!");
}
}
Here is code to set sound file.
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = new MediaPlayer();
AppLog.d("Created new Media player");
try {
mPlayer.setDataSource(fileName);
} catch (IOException e) {
AppLog.e("Can't open " + fileName + " file", e);
}
Before playing u should call the mPlayer.prepareAsync() function.
if you want to pause/play you have to use this code:
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
If you want to stop player use this:
if (mPlayer != null){
mPlayer.stop();
mPlayer.release();
}
mPlayer = null;
If you want to start song again use first functions and next with this steps
This code may help you..
#Override
protected void onDestroy() {
super.onDestroy();
destroyMediaPlayer();
}
private void destroyMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
Log.d("here", "destroy");
} catch (Exception e) {
e.printStackTrace();
}
}
}
SOLUTION 1
for this solution, I took some info from here
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
MediaPlayer mp;
/**
* remain false till media is not completed, inside OnCompletionListener make it true.
*/
private boolean initialStage = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (initialStage) {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
new Player()
.execute("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} else {
if (mp && !mp.isPlaying())
mp.start();
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp && mp.isPlaying())
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.stop();
mp.release();
mp = null;
initialStage = true;
}
}
});
}
/**
* preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread.
* #author piyush
*
*/
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mp.setDataSource(params[0]);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
initialStage = true;
mp.stop();
mp.reset();
}
});
mp.prepare();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mp.start();
initialStage = false;
}
public Player() {
progress = new ProgressDialog(PlayngUrlFiles.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
this.progress.show();
}
}
}
SOLUTION 2
in order to avoid data downloding, try this
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
boolean prepared;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
final MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
prepared = false;
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
prepared = true;
mp.start();
}
});
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
try {
if(!prepared) {
mp.prepareAsync();
prepared = true;
} else {
mp.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.pause();
}
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.stop();
prepared = false;
}
}
});
}
}
#MRodrigues was right about media player states. But instead of calling release() after stop, Modify your code as below.
Currently,
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
modify to,
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mp.isPlaying()) {
mp.prepare();
}
mp.start();
}
});
This code is to read a mp3 from raw folder,But I want to change my mp3 file to another file from sd card
its new code, music played but seekbar does not work properly, when i toch it seekbar come back to frist position
public class MainActivity extends Activity implements OnClickListener {
SeekBar seek_bar;
Button play_button, pause_button;
MediaPlayer mediaPlayer;
TextView text_shown;
Handler seekHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInit();
seekUpdation();
}
public void getInit() {
seek_bar = (SeekBar) findViewById(R.id.seek_bar);
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
text_shown = (TextView) findViewById(R.id.text_shown);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
String filePath = Environment.getExternalStorageDirectory() + "/Android/music.mp3";
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(filePath);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
});
mediaPlayer.prepareAsync();
seek_bar.setMax(mediaPlayer.getDuration());
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
seek_bar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
seek_bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seek_bar.setProgress(progress);
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
text_shown.setText("Playing...");
mediaPlayer.start();
break;
case R.id.pause_button:
mediaPlayer.pause();
text_shown.setText("Paused...");
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
finish();
}
}
Just move this line
seek_bar.setMax(mediaPlayer.getDuration());
to seekUpdation() after
seekHandler.postDelayed(run, 1000);
Replace
mediaPlayer = MediaPlayer.create(this, R.raw.my_file);
with:
String filePath = Environment.getExternalStorageDirectory() + "/randomDirectory/yourFile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
I'm trying to create an app that play a certain audio file, that was previously recorded, when I press a button or shake my phone. Here is my code.
public class Reproduzir extends Activity implements SensorEventListener{
MediaPlayer player = new MediaPlayer();
SensorManager sensor;
#Override
protected void onCreate(Bundle savedInstanceState ){
super.onCreate(savedInstanceState);
sensor= (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.reproduzir);
Button reproduzir = (Button) findViewById(R.id.reproduzir);
reproduzir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
play();
}
});
Button fechar= (Button) findViewById(R.id.fechar);
fechar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (player.isPlaying()) {
player.stop();
player.release();
}
finish();
}
});
}
public void play(){
try {
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onStart(){
super.onStart();
sensor.registerListener(this,sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.values[0]>10.2
||event.values[1]>10.2
||event.values[2]>10.2){
play();
}
}
}
My problem is that when I run it, I can only play it once. If I press the button a second time or shake it again, it does nothing. Can anyone help?
The easy fix is to simply add player.reset() in your play() method BEFORE calling player.setDataSource(...).
You can only call setDataSource(...) once without resetting the player. It is legal to call reset() in any state however (even if the player isn't yet initialized).
In other words, even if it's the first time you've called play() it is OK to use the following code in your play() method...
try {
player.reset();
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
}
// Your catch blocks here
Try to use:
mediaPlayer.reset()
after:
mediaPlayer.stop()
instead of release.
You can only set data source once.
in you code everytime the user presses the button you do this:
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
whice is wrong.
you need to setdata and prepare once and play how many times you want.
like so:
put this in you onCreate:
try {
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
in the onClick(View v), just have :
player.play();
Long story short - you have to use:
setLooping(true)
For more information about the Media Player check the post below. Take in mind the state diagram
http://developer.android.com/reference/android/media/MediaPlayer.html
MediaPlayer State diagram
i'm newbie, i'm tried to make play audio play and stop for 1 button only, but i'm in trouble now.
if i touch a button when audio is playing, it doesn't stop, even playing audio again and make a double sound.
here's my code
public class ProjectisengActivity extends Activity{
ImageButton mainkan;
MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
i'm create for android 3.0 (HoneyComb)
try below code in go function....
public void go() {
if(mp == null) {
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
}
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
}
It is simple, you should follow these steps to achieve this.
In your test2.xml create two buttons name start and stop.
Set the android:visibility attribute gone of stop button in xml file.
Now in your activity get the id of these two buttons and write the code for
starting and stopping of media player.
Set the visibility attribute gone on start click and visible of stop button,
follow its opposite on stop click.
I think you have wrong this line :
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
You create new instance every time user clicks the button, so it's never playing and starts again. Put this line into onCreate rather than go()
Try also this,
public class MainActivity extends Activity {
MediaPlayer mPlayer;
int flag = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (flag == 0) {
Log.v("Inside if", "Success" + "");
mPlayer = MediaPlayer.create(getApplicationContext(),
R.raw.sample);
mPlayer.start();
flag++;
} else {
Log.v("Inside else", "Success" + "");
mPlayer.stop();
mPlayer.release();
flag = 0;
}
}
});
}
}