I've tried to make a class that extends Mediaplayer and when I've played a sound I want to trigger an event handler in the activity calling the sound.
I Activity:
SoundPlayer soundPlayer = new SoundPlayer(BookInterface.this);
soundPlayer.playSound(this, R.raw.vroom);
And this is the SoundPlayer class:
public class SoundPlayer extends MediaPlayer{
BookInterface ownerActivity;
public SoundPlayer(BookInterface act){
ownerActivity = act;
}
public void playSound(Context context, int resId){
Log.d("Debug", "playSound is called");
MediaPlayer mp = new MediaPlayer();
try {
mp = MediaPlayer.create(context, resId);
mp.start();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Debug","Exception" + e);
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.d("Debug", "playSound.onCompletion is called");
mp.stop();
mp.release();
ownerActivity.eventHandler();
}
});
}
}
Why isnt the sound playing?
What am I doing wrong?
BR
Why you declare your MediaPlayer inside playSound method?
I think when playSound method execution is done your MediaPlayer cleared from memory, try to declare MediaPlayer as class variable like this:
public class SoundPlayer extends MediaPlayer{
BookInterface ownerActivity;
private MediaPlayer mp;
public SoundPlayer(BookInterface act){
ownerActivity = act;
}
public void playSound(Context context, int resId){
Log.d("Debug", "playSound is called");
try {
mp = MediaPlayer.create(context, resId);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.d("Debug", "playSound.onCompletion is called");
mp.stop();
mp.release();
ownerActivity.eventHandler();
}
});
mp.start();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Debug","Exception" + e);
e.printStackTrace();
}
}
}
Related
I have created android app to stream online radio station and I want to run it in background using service.How to create service to run media player in background?
Here is source code of the application:
public class MainActivity extends AppCompatActivity
{
private ImageButton buttonPlay,buttonStop,buttonPause;
private String STREAM_URL = "http://178.149.86.162:8000/";
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);
buttonStop = (ImageButton) findViewById(R.id.buttonStopPlay);
buttonPause = (ImageButton) findViewById(R.id.buttonPause);
mPlayer = new MediaPlayer();
buttonPlay.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
mPlayer.reset();
mPlayer.setDataSource(STREAM_URL);
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
startService();
}
});
buttonStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mPlayer.stop();
stopService();
}
});
buttonPause.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mPlayer.pause();
stopService();
}
});
playbackServiceIntent = new Intent(this, BackgroundService.class);
}
private void startService()
{
startService(new Intent(MainActivity.this,BackgroundService.class));
}
private void stopService()
{
stopService(new Intent(MainActivity.this,BackgroundService.class));
}
}
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL = "http://178.149.86.162:8000/";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
mediaPlayer = new MediaPlayer();
try
{
mediaPlayer.setDataSource(STREAM_URL);
} catch (IOException e)
{
e.printStackTrace();
}
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
I tried all the solutions provided in this site & still i am getting this error.Don't know why it happen! please help me.
Here my code.
MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.square);
mediaPlayer.setOnErrorListener(MainActivity.this);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mWinMusic[blocks].release();
}
});
public boolean onError(MediaPlayer mp, int what, int extra) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.square);
mp.start();
return true;
}
Create player like this and add mediaPlayer.prepare(); and when ready then start in onPrepared()
public class MainActivity extends Activity {
MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.square);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(MainActivity.this, "Some problem ", Toast.LENGTH_LONG).show();
return false;
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(MainActivity.this, "track completed", Toast.LENGTH_SHORT).show();
//mWinMusic[blocks].release();
}
});
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Some problem " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
I am fairly new to programming and having a tough time with a small problem. I have created an object which is initialized easily and starts working, how do i stop that object from functioning.
Following is my code:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
animationFart();
playRandomSound();
}
private void playRandomSound() {
// TODO Auto-generated method stub
int randomInt = (new Random().nextInt(soundList.size()));
int sound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(btn.getContext(), sound);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
});
How can i stop this with the press of a button.
Define MediaPlayer mp; globally and use mp.stop();:
if (mp!=null && mp.isPlaying()) {
mp.stop();
}
use this class
public class AudioPlayer {
private MediaPlayer mediaPlayer;
public void play(Context context, int resId) {
stop();
mediaPlayer = MediaPlayer.create(context, resId);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mediaPlayer.start();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
public boolean isPlaying() {
return mediaPlayer != null;
}
}
I use media player to play sounds on my application. It works just fine.
I am playing sound on a separated thread. Even thought, part of the sound plays before activity appear.
I tried to play sound onCreate method. it didn't work. onStart and
onResume. it has some problems. it plays every time activity resumed.
sometimes while I am not even touching the device!
What is the best way to play sound after activity appears?
public boolean played = false;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (!played)
Settings.playSound(dvd.titleImageName.replace("png", "mp3"), this);
played = true;
}
public static MediaPlayer mp = null;
public static void playSound(String fileName, Context c)
{
//MediaPlayer mp = MediaPlayer.create(c, resId);
if (mp!=null)
{
mp.stop(); //error
mp.reset();
mp.release();
}
mp = new MediaPlayer();
AssetFileDescriptor descriptor;
try {
descriptor = c.getResources().getAssets().openFd("sounds/" + fileName);
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mp == null) return;
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
});
mp.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
}
});
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mp.start();
}
}).start();
}
Your played variable only works while activity is alive. If it gets killed, played doesn't retain. For example, rotate your device an you'll hear sound playing again.
save state (played) in onSavedInstanceState bundle and restore it in onCreate
Play in in OnCreate or onResume
I want to use MediaPlayer android, using this code, but I get an error, there's a way to fix this code, or can anyone bring me a better example for this?
try {
MediaPlayer player = new MediaPlayer();
player.setDataSource("/LFP/res/raw/Allen.mp3");
player.prepare();
player.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.MotionEvent;
import android.widget.MediaController;
import android.widget.TextView;
import java.io.IOException;
public class AudioPlayer extends Activity implements OnPreparedListener,
MediaController.MediaPlayerControl{
private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);
((TextView)findViewById(R.id.now_playing_text)).setText(audioFile);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return false;
}
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
}
This worked fine for me.Hope it works for you also.
use
mediaplayer.prepareAsync()
and
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
instead it
Here I am keeping my audio file in asset. Following code works,
MediaPlayer mp= new MediaPlayer();
AssetFileDescriptor afd = null;
try {
afd =getActivity().getBaseContext().getAssets().openFd("myAudio.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (IOException e) {
e.printStackTrace();
}