im trying to play 1 of 2 sounds , correct.mp3 or incorrect.mp3, which is stored in my assets folder. This is the code for my service:
public class MinesweeperSound extends Service {
MediaPlayer player;
public int onStartCommand(Intent intent, int flags, int startId) {
try {
String audioFile = null;
audioFile = intent.getStringExtra("filename");
AssetFileDescriptor afd = getAssets().openFd(audioFile);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor());
player.prepare();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
}catch (IOException e){
e.printStackTrace();
}
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
here is how i call it in Activity:
Intent correctIntent = new Intent(getApplicationContext(), MinesweeperSound.class);
correctIntent.putExtra("filename", "correct.mp3");
startService(correctIntent);
for some reason it is not playing any sound, any help is good, thanks
You should set on prepare listener before calling prepare
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { #Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); } });
player.prepare();
MediaPlayer.prepare() is a synchronous method. If you use it then you dont need a onPrepareListener.
Otherwise use
prepareAsync()
instead of
prepare()
i finally figured it out. I needed to add parameters to the .setDataSource method. here is the working code:
MediaPlayer player = null;
public int onStartCommand(Intent intent, int flags, int startId){
try {
String audioFile = null;
audioFile = intent.getStringExtra(PowerUpUtils.MINESWEEPER_TILE_RESULT);
AssetFileDescriptor afd = getBaseContext().getAssets().openFd(audioFile);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
}catch (IOException e){
e.printStackTrace();
}
player.start();
return Service.START_STICKY;
}
also, calling start() after the try-catch block seemed to be part of the fix.
Related
Help me I am stuck on this, mediaPlayer.setDataSource() is giving error when clicking on any song list in recycler view. I am new to Android Studio as I have started it past year.
Here is the video of what is happening in my app
java.lang.IllegalStateException
at android.media.MediaPlayer._setDataSource(Native Method)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1296)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1279)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1261)
at android.media.MediaPlayer.attemptDataSource(MediaPlayer.java:1155)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1112)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1019)
at com.example.musify.MainActivity$10.run(MainActivity.java:454)
at java.lang.Thread.run(Thread.java:919)**
Always getting error in onchanged method setDataSource:
#Override
public void onChanged(int position) {
currentSongNumber = position;
CreateNotification.createNotification(MainActivity.this,musicLists.get(currentSongNumber),R.drawable.ic_baseline_pause_24,currentSongNumber,musicLists.size()-1);
if(mediaPlayer.isPlaying())
{
mediaPlayer.pause();
mediaPlayer.stop();
}
new Thread(new Runnable() {
#Override
public void run() {
try {
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//this is the place where i am getting error although i have reset on instance of mediaplayer
mediaPlayer.setDataSource(MainActivity.this, musicLists.get(currentSongNumber).getMusicFile());
MainActivity.this.runOnUiThread(() -> {
// musicbar_artist.setText(musicLists.get(currentSongNumber).getArtist());
musicbar_name.setText(musicLists.get(currentSongNumber).getTitle());
});
} catch (IOException e) {
new Handler(Looper.getMainLooper()).post(() -> Toast.makeText(MainActivity.this, "Unable to Play Track!", Toast.LENGTH_SHORT).show());
e.printStackTrace();
}
try {
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
final int getTotalDuration = mp.getDuration();
String generateDuration = String.format(Locale.getDefault(),"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(getTotalDuration),
TimeUnit.MILLISECONDS.toSeconds(getTotalDuration)-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(getTotalDuration)));
endTime.setText(generateDuration);
isPlaying = true;
mp.start();
playSeekbar.setMax(getTotalDuration);
playpauseImage.setImageResource(R.drawable.pause_svg);
}
});
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final int getCurrentDuration = mediaPlayer.getCurrentPosition();
String generateDuration = String.format(Locale.getDefault(),"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(getCurrentDuration),
TimeUnit.MILLISECONDS.toSeconds(getCurrentDuration)-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(getCurrentDuration)));
playSeekbar.setProgress(getCurrentDuration);
startTime.setText(generateDuration);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.reset();
String tm = "00:00";
startTime.setText(tm);
timer.purge();
timer.cancel();
isPlaying = false;
playpauseImage.setImageResource(R.drawable.ic_baseline_play_arrow_24);
playSeekbar.setProgress(0);
musicAdapater.update(musicLists);
musicRecyclerV.scrollToPosition(0);
// starts next music
onNext();
}
});
}
},1000,1000);
}
#Override
public void onPlay() {
CreateNotification.createNotification(MainActivity.this,musicLists.get(currentSongNumber),R.drawable.ic_baseline_pause_24,currentSongNumber,musicLists.size()-1);
isPlaying = true;
playpauseImage.setImageResource(R.drawable.pause_svg);
mediaPlayer.start();
musicLists.get(currentSongNumber).setPlaying(true);
musicbar_name.setText(musicLists.get(currentSongNumber).getTitle());
// musicbar_artist.setText(musicLists.get(currentSongNumber).getArtist());
musicAdapater.update(musicLists);
musicRecyclerV.scrollToPosition(currentSongNumber);
onChanged(currentSongNumber);
}
#Override
public void onPrev() {
int prevsongnumber = currentSongNumber-1;
if(prevsongnumber<0)
{
prevsongnumber = musicLists.size()-1;
}
CreateNotification.createNotification(MainActivity.this,musicLists.get(prevsongnumber),R.drawable.ic_baseline_pause_24,prevsongnumber,musicLists.size()-1);
musicLists.get(currentSongNumber).setPlaying(false);
musicLists.get(prevsongnumber).setPlaying(true);
musicbar_name.setText(musicLists.get(prevsongnumber).getTitle());
// musicbar_artist.setText(musicLists.get(prevsongnumber).getArtist());
musicAdapater.update(musicLists);
musicRecyclerV.scrollToPosition(prevsongnumber);
onChanged(prevsongnumber);
}
#Override
public void onPaused() {
CreateNotification.createNotification(MainActivity.this,musicLists.get(currentSongNumber),R.drawable.ic_baseline_play_arrow_24,currentSongNumber,musicLists.size()-1);
isPlaying = false;
mediaPlayer.pause();
playpauseImage.setImageResource(R.drawable.ic_baseline_play_arrow_24);
}
#Override
public void onNext() {
int nextsongnumber = currentSongNumber+1;
if(nextsongnumber>=musicLists.size())
{
nextsongnumber = 0;
}
CreateNotification.createNotification(MainActivity.this,musicLists.get(nextsongnumber),R.drawable.ic_baseline_pause_24,nextsongnumber,musicLists.size()-1);
musicLists.get(currentSongNumber).setPlaying(false);
musicLists.get(nextsongnumber).setPlaying(true);
musicbar_name.setText(musicLists.get(nextsongnumber).getTitle());
// musicbar_artist.setText(musicLists.get(nextsongnumber).getArtist());
musicAdapater.update(musicLists);
musicRecyclerV.scrollToPosition(nextsongnumber);
onChanged(nextsongnumber);
}
MediaPlayer.create() is better than setDatasource
got this from a YouTube comment!!
if(mediaPlayer.isPlaying())
{
mediaPlayer.pause();
}
mediaPlayer.stop();
mediaPlayer.release();
// passing applicationContext() and uri file of currentsongnumber
mediaPlayer = MediaPlayer.create(MainActivity.this, musicLists.get(currentSongNumber).getMusicFile());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
MainActivity.this.runOnUiThread(() -> {
// musicbar_artist.setText(musicLists.get(currentSongNumber).getArtist());
musicbar_name.setText(musicLists.get(currentSongNumber).getTitle());
});
try {
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
I am making an application which play background music. And when my phone's screen goes off(or sleep) then the music stops and I want it to also play after the screen goes's off.
This is My code.
MediaPlayer ring= MediaPlayer.create(MainActivity.this,R.raw.backgroundmusic);
ring.start();
ring.setLooping(true);
MediaPlayer class can be used to control playback of audio/video files and streams. An example on how to use the methods in this class can be found in VideoView.
MediaPlayer
public class SoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Intent svc=new Intent(this, SoundService.class);
startService(svc);
Make sure You've added your service to the menifest.
<service android:enabled="true" android:name=".SoundService" />
You should consider using Service.
I have been working on an audio stream app but I need clarity on a variety of issues. First of all, I am playing the audio file with a bound service and I have a play-pause button` that toggles player on and off.
These are the issues i have with my code:
Media player gets instantiated each time I press play button but that is not what because I also need to pause playback when needed.
Playback is very slow. It takes a lot of time for the mediaplayer to prepare and stream.
Sometimes media player gets initialized twice if the user vigorously toggles the playpause button.
Here the code:
Music Player Activity
btn_play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!playPause) {
btn_play_pause.setImageResource(R.drawable.pause_button);
if (initialStage) {
musicService.play();
Toast.makeText(MusicPlayerActivity.this, "Playing started", Toast.LENGTH_SHORT).show();
}
playPause = true;
} else {
btn_play_pause.setImageResource(R.drawable.play_button);
Toast.makeText(MusicPlayerActivity.this, "Playing paused", Toast.LENGTH_SHORT).show();
playPause = false;
musicService.pause();
}
}
});
}
Music Service
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener{
private final IBinder mBinder = new MusicService.AudioBinder();
private MediaPlayer mediaPlayer;
private AudioManager audioManager;
private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "Network Error", Toast.LENGTH_LONG).show();
mediaPlayer.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
try {
mp.setDataSource(stream_source);
mp.prepareAsync();
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
mediaPlayer = mp;
}
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer = mp;
}
public class AudioBinder extends Binder {
public MusicService getService() {
//Return this instance of RadioBinder so clients can call public methods
return MusicService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction() != null) {
switch (intent.getAction()) {
case Constants.ACTION_STOP_AUDIO_SERVICE:
hideNotification();
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("close_activity",true);
this.startActivity(i);
break;
case Constants.ACTION_STREAM_PLAY_PAUSE:
if (isPlaying()) {
pause();
showNotification();
stopForeground(false); // stop making it a foreground service but leave the notification there
} else {
play();
showNotification();
}
break;
default:
break;
}
}
return START_STICKY;
}
#Override
public void onCreate() {
setUpAudioManager();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
public void play() {
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
showNotification();
}
public void pause() {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
audioManager.abandonAudioFocus(audioFocusChangeListener);
}
showNotification();
}
public boolean isPlaying() {
return mediaPlayer != null && (mediaPlayer.isPlaying());
}
#Override
public boolean stopService(Intent name) {
if (mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
return super.stopService(name);
}
public void hideNotification() {
stopForeground(true);
}
#Override
public void onDestroy() {
if(mediaPlayer!= null){
mediaPlayer.release();
}
super.onDestroy();
}
public void releaseTrack(){
if(mediaPlayer!= null){
mediaPlayer.release();
}
}
}
This is my first question. It is giving NullPointerException in media.release() line. Exact output is NullPointerException (#ProgressDetailRecyclerViewAdapter$5:onCompletion:308) {main}
public void play(String fileURL) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(fileURL);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release(); //line 308
mediaPlayer = null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer **mp**) {
**mediaPlayer**.release(); //line 308
mediaPlayer = null;
}
use the right object mp instead of mediaPlayer inside this method
Try this
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release(); //line 308
mp= null;
}
});
The variable that gets passed to your onCompletion method is named mp, not mediaPlayer. It's possible your mediaPlayer variable has been nulled since it was initialized, causing the error. Change the code to:
#Override
public void onCompletion(MediaPlayer mp) {
mp.release(); //line 308
mp = null;
}
I try to replay a sound when I click on a button. But I get the Error (-19, 0) (what ever this means^^)
My code:
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.start();
}
});
What is my mistake?
I was getting the same problem, I solved it by adding the following code:
mp1 = MediaPlayer.create(sound.this, R.raw.pan1);
mp1.start();
mp1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
You need to release the previous media player before starting the new one.
Declare MediaPlayer as a instance variable and then:
mp = null;
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.start();
}
});
Or in your case, since you always play the same sound you don't need to release the player and create a new one, simply reuse the old one.
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.prepare(); // Blocking method. Consider to use prepareAsync
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.stop();
mp.start();
}
});
I sloved this problem by this code:
public static void playSound() {
mMediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor afd = context.getAssets().openFd("type.mp3");
mMediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
arg0.release();
}
});
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i hope to help you.