in my simple player i have play, and stop buttons and play and pause media player work fine, now after click on stop and play again, media player don't work and i'm not sure whats problem to resolve that
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
playMonthLesson();
...
}
#SuppressLint("DefaultLocale")
public void playMonthLesson() {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(CoreApplication.MEDIAFOLDER + "/" + lesson.getFilename());
mediaPlayer.prepare();
mediaPlayer.start();
lesson_play.setImageResource(R.drawable.ic_pause);
int totalDuration = mediaPlayer.getDuration();
// set Progress bar values
lesson_progress_bar.setProgress(curretLessonProgress);
lesson_progress_bar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#OnClick(R.id.lesson_play)
public void lesson_play(View view) {
if (mediaPlayer == null) {
playMonthLesson();
} else if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
mediaPlayer.pause();
// Changing button image to play button
lesson_play.setImageResource(R.drawable.ic_play);
}
} else {
// Resume song
if (mediaPlayer != null) {
mediaPlayer.start();
// Changing button image to pause button
lesson_play.setImageResource(R.drawable.ic_pause);
}
}
}
#OnClick(R.id.lesson_stop)
public void setLesson_stop(View view) {
if (mediaPlayer != null) {
mediaPlayer.stop();
lesson_play.setImageResource(R.drawable.ic_play);
lesson_progress_bar.setProgress(0);
}
}
According to the MediaPlayer life cycle, which you can view in the Android API guide, I think that you have to call reset() instead of stop(), and after that prepare again the media player (use only one) to play the sound from the beginning. Take also into account that the sound may have finished. So I would also recommend to implement setOnCompletionListener() to make sure that if you try to play again the sound it doesn't fail.
The problem is that when you stop mediaplayer and click on play again your call will go to mediaplayer.play() as mediaplayer is not null.
You will have to null the mediaPlayer on stop method. Now, once you stop mediaplayer and again click on play it will call playMonthLesson();
#OnClick(R.id.lesson_stop)
public void setLesson_stop(View view) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer = null;
lesson_play.setImageResource(R.drawable.ic_play);
lesson_progress_bar.setProgress(0);
}
}
change this code too,
#SuppressLint("DefaultLocale")
public void playMonthLesson() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setDataSource(CoreApplication.MEDIAFOLDER + "/" + lesson.getFilename());
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
lesson_play.setImageResource(R.drawable.ic_pause);
int totalDuration = mediaPlayer.getDuration();
}
});
mediaPlayer.prepareAsync();
// set Progress bar values
lesson_progress_bar.setProgress(curretLessonProgress);
lesson_progress_bar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I have searched and researched stackoverflow and google but can't find any answer to MY question. I've found other question and answers but that were related to sounds saved in the app but I'm creating an app which gets data from Parse server, so it gets mp3 files and display these in listview and than when an item is clicked it plays that track. But here comes the problem: When you play a sound and click on another one, the first just doesn't stop and the second starts to play.
I have tried with the following code but it's just not working.
Here's my code:
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final MediaPlayer mediaPlayer = new MediaPlayer();
final MediaPlayer scndmediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
scndmediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (mediaPlayer.isPlaying()) {
Toast.makeText(getContext(), "First is playing", Toast.LENGTH_SHORT).show();
try {
mediaPlayer.stop();
scndmediaPlayer.setDataSource(audioFileURL);
scndmediaPlayer.prepare();
scndmediaPlayer.start();
//soundtoolbar.setTitle(name);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
if (scndmediaPlayer.isPlaying()){
scndmediaPlayer.stop();
}
Toast.makeText(getContext(), "First is starting", Toast.LENGTH_SHORT).show();
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
mediaPlayer.start();
soundtoolbar.setTitle(name);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() || scndmediaPlayer.isPlaying()) {
mediaPlayer.pause();
scndmediaPlayer.pause();
playPause.setBackground(getContext().getDrawable(R.drawable.ic_play_arrow_white_24dp));
} else {
mediaPlayer.start();
scndmediaPlayer.start();
playPause.setBackground(getContext().getDrawable(R.drawable.ic_pause_white_24dp));
}
}
});
}
});
I've created 2 mediaplayers with the code above and when user clicks the play button it first checks if any of the player is running.
I'm trying to achieve the following: When user clicks the play button it checks if the (1st) mediaPlayer is running or not. If it's running, it has just to stop it and launch (2nd) scndmediaPlayer or viceversa... if second is playing it stops that and launch first one. so it will create a loop: 1st is playing? User clicks another button stop first. Launch second. User clicks another button. First is playing? No. Second is playing? Yes. Stop the second and launch the first.
But can't find where is the problem in my code.
Please help me with this. I'm trying to resolve it from 2 days but I'm unable...
Thanks :)
EDIT: I tried using one MediaPlayer and do the following: Check if mediaplayer is playing! No it isn't playing. Start it. User clicks the button again and it stops the mediaplayer and start it with new audioFileUrl. BUT. MediaPlayer is forgetting that it's playing. Seems like it just starts the track and than forget and to check if it's true i set a Toast: when mediaplayer isn't playing the toast shows and it's showing every time I click a track in the list which means it forget that it has a track which is playing...
EDIT 2: I managed to do the following: It plays the track. User clicks another track. It stops the mediaplayer but doesn't play the new track. User click once again. It plays the new track. User clicks the new track and the app crashes...
EDIT 3: Posting my entire class:
public class MyAdapter extends ParseQueryAdapter<ParseObject> {
public Button playPause, next, previous;
public Toolbar soundtoolbar;
boolean isPlaying = false;
public MyAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("MyClass");
query.orderByDescending("createdAt");
return query;
}
});
}
#Override
public View getItemView(final ParseObject object, View v, final ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.activity_audio_files_item, null);
}
super.getItemView(object, v, parent);
final Button play = (Button) v.findViewById(R.id.play);
playPause = TabFragment1.playPause;
next = TabFragment1.next;
previous = TabFragment1.previous;
soundtoolbar = TabFragment1.soundtoolbar;
final ParseFile descr = object.getParseFile("audiofile");
final String name = object.getString("name");
final String audioFileURL = descr.getUrl();
final SlidingUpPanelLayout slidingUpPanelLayout = TabFragment1.spanel;
play.setText(name);
final MediaPlayer mediaPlayer = new MediaPlayer();
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPlaying != true) {
Toast.makeText(getContext(), name+" is playing", Toast.LENGTH_SHORT).show();
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
soundtoolbar.setTitle(name);
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
mediaPlayer.start();
isPlaying = true;
}
});
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e2) {
e2.printStackTrace();
} catch (IllegalStateException e3) {
e3.printStackTrace();
} catch (IOException e4) {
e4.printStackTrace();
} catch (NullPointerException e5) {
e5.printStackTrace();
}
} else {
mediaPlayer.stop();
Toast.makeText(getContext(), "Starting "+name, Toast.LENGTH_SHORT).show();
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
soundtoolbar.setTitle(name);
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
mediaPlayer.start();
}
});
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e2) {
e2.printStackTrace();
} catch (IllegalStateException e3) {
e3.printStackTrace();
} catch (IOException e4) {
e4.printStackTrace();
} catch (NullPointerException e5){
e5.printStackTrace();
}
}
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
playPause.setBackground(getContext().getDrawable(R.drawable.ic_play_arrow_white_24dp));
} else {
mediaPlayer.start();
playPause.setBackground(getContext().getDrawable(R.drawable.ic_pause_white_24dp));
}
}
});
}
});
return v;
}
}
Somebody please help...
i suggest you to checkout SoundPool . İt ll helps you. And one more , may be you ll put media urls to array or something like this.And use one mediaPlayer By the way, you ll avoid from two mediaPlayer and avoid from memory leak.
http://developer.android.com/reference/android/media/SoundPool.html
Playing .wav file using MediaPlayer class. As I need to loop the Audio I've set .setLooping(true); . So obviously, the doubt is how do I add a delay each time the audio plays, say I want a delay of 5000 .
The answers to similar questions here doesn't work in my case. Any help would be appreciated. Here is my code:
Button Sample = (Button)findViewById(R.id.samplex);
Sample.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filePath = Environment.getExternalStorageDirectory()+"/myAppCache/wakeUp.wav";
try {
mp.setDataSource(filePath);
mp.prepare();
mp.setLooping(true);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
You need to register 2 listeners (on completion and on error) and then you would need to delay next play in on completion callback. Reason for the error listener is to return true to avoid calling on completion event whenever there is an error - explanation here
private final Runnable loopingRunnable = new Runnable() {
#Override
public void run() {
if (mp != null) {
if (mp.isPlaying() {
mp.stop();
}
mp.start();
}
}
}
mp.setDataSource(filePath);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
button.postDelayed(loopingRunnable, 5000);
}
});
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
...
return true;
});
mp.prepare();
// no need to loop it since on completion event takes care of this
// mp.setLooping(true);
Whenever your destruction method is (Activity.onDestroyed(), Fragment.onDestroy(), View.onDetachedFromWindow()), ensure you are removing the runnable callbacks, e.g.
#Override
protected void onDestroy() {
super.onDestroy();
...
button.removeCallbacks(loopingRunnable);
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
}
I am building an app which plays several videos, and I have two different user scenarios :
Scenario 1. While video 'A' is playing, if user clicks next button, then it stops and play the next video 'B'.
Scenario 2. Play video 'A', and if it's done, user clicks next button and it plays video 'B'.
For the first scenario, I used mediaPlayer.isPlaying() method to detect if it is in Started state and it works fine. However, if I use the same code for the second scenario, isPlaying() throws IllegalStateException.
Here's my code for playing videos :
private void playVideos(SurfaceHolder holder) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(holder);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + video_files[mCounter]);
mediaPlayer.setDataSource(this, uri);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (mCounter <= 8) {
onVideoCompletion(mediaPlayer);
} else {
mediaPlayer.stop();
mediaPlayer.release();
}
}
});
} catch (IOException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalStateException e) {
}
}
Also, here's my button listener to play next video :
nextBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
mCounter += 1;
if (mCounter <= 8) {
playVideos(holder);
}
}
});
One way that I tried to hack this issue was using a boolean variable instead of isPlaying() method. For example,
boolean mIsPlaying = false;
...
// in button listener
if(mIsPlaying) {
mediaPlayer.stop();
mediaPlayer.release();
}
...
// in playVideos() function
mediaPlayer.start();
mIsPlaying = true;
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (mCounter <= 8) {
onVideoCompletion(mediaPlayer);
} else {
mediaPlayer.stop();
mediaPlayer.release();
}
}
});
That works for my both of scenario, but I'm not sure if it's the correct way to do it. Isn't there any way to detect whether mediaPlayer is in Stopped state?
I took a look at Google's Documentation which you can find here. You can only know if the player isPlaying(); or isLooping(); ... So no, there is not an "easy" or "short" way to achieve what you want. Hope it helped.
Making an app and streaming audio from site. I've got a menu and when I click the button to open the radio activity it can take from 8-20 seconds to load and sometimes force closes. Any help would be awesome thanks.
Code:
public class Radio extends Activity {
private MediaPlayer mp;
private ImageButton pauseicon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
getActionBar().setDisplayHomeAsUpEnabled(true);
/**
* Play button click event plays a song and changes button to pause
* image pauses a song and changes button to play image
* */
String res = "http://216.235.91.36/play?s=magic24point7&d=LIVE365&r=0&membername=&session=magic24point7:0&AuthType=NORMAL&app_id=live365%3ABROWSER&SaneID=24.79.96.172-13316781890137014897763&tag=live365";
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if (mp.isPlaying()) {
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if (mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (mp != null) {
if (mp.isPlaying())
mp.stop();
mp.release();
}
// there is no reason to call super.finish(); here
// call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
Use prepareAsync() and setOnPreparedListener() instead of prepare(). prepare() blocks the UI thread until it returns and is not recommended for a stream. This may be the cause your crash.
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
mp.start();
}
});
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
http://developer.android.com/reference/android/media/MediaPlayer.html#prepare()
Prepares the player for playback, synchronously. After setting the datasource and the display surface, you need to either call prepare() or prepareAsync(). For files, it is OK to call prepare(), which blocks until MediaPlayer is ready for playback.
Otherwise I think the network is your bottleneck. The fastest way to speed things up is to ensure your server/client communication is quick. There doesn't seem to be anything inherently slow about your code.
In the application I am currently writing, a user is able to select an entry from the database and play the contents of that entry: an entry is made up of a number of sound files (without a limit). In my application, I return the URI locations of the sound files of an entry (which have been stored in my database) in a List. The code is as follows:
public void audioPlayer() {
// set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
DatabaseHandler db = new DatabaseHandler(this);
Entry retrieveEntry = new Entry();
retrieveEntry = db.getEntry();
List<String> path = retrieveEntry.getAudioUri();
path.size();
System.out.println("PATH SIZE: " +path.size());
System.out.println("FILEZ: " + path);
Iterator<String> i = path.iterator();
String myAudio;
int count = 0;
while (i.hasNext()) {
System.out.println(count);
myAudio = i.next();
System.out.println("MY AUDIO: " + myAudio);
MediaPlayer player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
player.stop();
player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
count++;
}
}
My users require that there be user input for playing a file - is there a way to play the first file, then wait for the user to press the button, then play the second file, then wait for the user to press the button, etc.? At the moment, when the play button is pressed, all of the sound files that have been returned get played at the same time, rather than one after the other.
Thanks in advance for any help provided!
You can use this class to play a playlist. This will start one audio, when that audio finishes, it will start playing next audio till the end of the list. If you want to play the playlist in looping i.e start first audio after reaching end, then pass isLooping=true in startPlayingPlaylist(list,looping)
AudioPlayer player = new AudioPlayer();
player.startPlayingPlaylist(list, false);
Class
public class AudioPlayer{
MediaPlayer player = null;
ArrayList<String> playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list, boolean looping){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.setLooping(looping);
player.start();
// Set onCompletion listener
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(player.isLooping()==false){
player.release();
player = null;
}
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
Edit:
The class below receives a list of audios, then plays first Audio. It plays next audio when user calls startNextAudio() You can use any one of these according to your requirements
public class AudioPlayer{
MediaPlayer player = null;
ArrayList playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.start();
// Set onCompletion listener
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void startNextAudio(){
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
Log.i("AudioPlayer","Playlist reached at the end");
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
One approach would be to implement the MediaPlayer.OnCompletionListener interface. This gives you the MediaPlayer.onCompletion() callback method which you could use like so:
#Override
public void onCompletion(MediaPlayer mp) {
if (i.hasNext) {
// ...hand mp the next file
// ...show the user the 'play next' button
}
}
Note you also will need to call the MediaPlayer.setOnCompletionListener() method in your setup.