Android MedialPlayer, where to release and create? - android

I am trying to play a sound when button is pressed. To do so, I tried few methods :
1 : Created a MediaPlayer under and played it when button is pressed like this :
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(MainActivity.this, R.raw.bell);
mp.setLooping(false);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mp.seekTo(0);
mp.start();
}
});
}
This method worked like charm. But then I wanted to conserve memory and wanted to release MediaPlayer when activity is in background. So I added this
#Override
protected void onPause() {
// TODO Auto-generated method stub
mp.release();
super.onPause();
}
But now, when activity comes back in foreground it throws an error ( because MediaPlayer is created under OnCreate).
So, I thought to create it under onResume since it is always called.
#Override
protected void onResume() {
// TODO Auto-generated method stub
mp = MediaPlayer.create(MainActivity.this, R.raw.bell);
mp.setLooping(false);
super.onResume();
}
It worked.
Full code is like this :
package com.example.learn;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
mp.release();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
mp = MediaPlayer.create(MainActivity.this, R.raw.bell);
mp.setLooping(false);
super.onResume();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1: {
mp.seekTo(0);
mp.start();
}
}
}
}
just thinking have I done it right? Are there better and easier ways?

By looking on your code I think you have done it in a right way. You can Create that in onResume as it is always called. On Create is Called for the first time only.
And Yes ALWAYS call
mediaPlayer.relaese();
instead of
mediaPlayer.stop();
Everything in your code is looking right. For more accuracy you can have a glance on this
LINK

Related

Get an error while i try to put Insterstitial Ads

i ask here because i can't put instertital ads in my app. I get like 20 errors when i put the code below the saved Instance.
I had other app and i never had problems, but now i just can't.
In the section of Toast (below ad code) i get this error:
Multiple markers at this line
- Syntax error on token "(", invalid VariableDeclaratorId
- Syntax error on tokens, delete these tokens
- Syntax error on token "makeText", Identifier expected after
this token
- Syntax error on token ")", delete this token
Below toast, on btnSwitch i get this errors:
Multiple markers at this line
- Return type for the method is missing
- Syntax error on token ".", ... expected
- Syntax error on token ")", { expected after this token
- Syntax error on token "btnSwitch", VariableDeclaratorId expected after
this token
- Syntax error, insert ";" to complete FieldDeclaration
package lol.flashlight;
Then here:
ImageView Facebook = (ImageView) findViewById(R.id.imageView3);
Facebook.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
i get this errors:
Multiple markers at this line
- Syntax error, insert "}" to complete
MethodBody
- Syntax error, insert ")" to complete
Expression
- Syntax error, insert ";" to complete
Statement
- Syntax error, insert "}" to complete
ClassBody
...I get MORE errors
I tried to put it at the final but anyway i get these errors, what can i do?
I let my full code if u wanna check:
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements AdListener {
ImageView btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the interstitial
interstitial = new InterstitialAd(this, "fgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfg");
// Create ad request
AdRequest adRequest = new AdRequest();
// Begin loading your interstitial
interstitial.loadAd(adRequest);
// Set Ad Listener to use the callbacks below
interstitial.setAdListener(this);
}
#Override
public void onReceiveAd(Ad ad) {
Log.d("OK", "Received ad");
if (ad == interstitial) {
interstitial.show();
}
}
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
Toast.makeText(MainActivity.this, "Touch amumu's body to play a sound!", Toast.LENGTH_SHORT).show();
// flash switch button
btnSwitch = (ImageView) findViewById(R.id.imageView1);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
ImageView Facebook = (ImageView) findViewById(R.id.imageView3);
Facebook.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mp = MediaPlayer.create(MainActivity.this, R.raw.draven);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
Intent facebookIntent = new Intent(Intent.ACTION_SEND);
facebookIntent.setType("text/plain");
facebookIntent.setPackage("com.facebook.katana");
facebookIntent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=lol.flashlight");
startActivity(facebookIntent);
}});
ImageView Twitter = (ImageView) findViewById(R.id.imageView4);
Twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.draven);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
//al apretar click en el boton Ir a Web abre el browser con la pág: google.com
Intent browserIntent =
new Intent(Intent.ACTION_VIEW,
Uri.parse("https://twitter.com/intent/tweet?text=https://play.google.com/store/apps/details?id=lol.flashlight%20-%20This%20app%20is%20amazing,%20i%20love%20it!"));
startActivity(browserIntent);
}});
//OnClick del View :D
ImageView Ez = (ImageView) findViewById(R.id.imageView2);
Ez.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
mp = MediaPlayer.create(MainActivity.this, R.raw.amumu);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}});
//OnClick del View :D
// ImageView Mundo = (ImageView) findViewById(R.id.imageView6);
// Mundo.setOnClickListener(new OnClickListener(){
// public void onClick(View v) {
// TODO Auto-generated method stub
//
// mp = MediaPlayer.create(MainActivity.this, R.raw.mundo);
//mp.setOnCompletionListener(new OnCompletionListener() {
// #Override
// public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// mp.release();
// }
// });
// mp.start();
//}});
//OnClick del View :D
// ImageView Orianna = (ImageView) findViewById(R.id.imageView7);
// Orianna.setOnClickListener(new OnClickListener(){
//public void onClick(View v) {
// TODO Auto-generated method stub
// mp = MediaPlayer.create(MainActivity.this, R.raw.orianna);
// mp.setOnCompletionListener(new OnCompletionListener() {
// #Override
// public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// mp.release();
// }
// });
// mp.start();
//}});
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
// Turning Off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
// Playing sound
// will play button toggle sound on flash on / off
private void playSound(){
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.playbutton);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.rayo);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.on);
}else{
btnSwitch.setImageResource(R.drawable.off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
your imports here are wrong, because they import from legacy admob:
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;
You have to import from .gms Google Play Services Admob:
import com.google.android.gms.ads.*
Also note that all the code below Toast.makeText(MainActivity.this, "Touch amumu's body to play a sound!", Toast.LENGTH_SHORT).show(); in your example is outside of any method (!) ..this is causing the dozens of compile errors. ==> move that code into some method

How to release Android MediaPlayer?

Momentarily I have in LogCat "Mediaplayer error (-19,0)" after repeated plays. So the first time(s) I play my app everything is ok, but after a time the Sound doesn't work anymore.
public TextView tw;
MediaPlayer mpButtonKlick;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.app);
tw = (TextView)findViewById(R.id.Text);
tw.setOnClickListener(this);
mpButtonKlick = MediaPlayer.create(this, R.raw.sound);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mpButtonKlick.start();
you release like this:
mpButtonKlick.release();
mpButtonKlick = null;
It's good practice to also release the MediaPlayer object when you start playing new media to ensure that there is just one instance running.
private void stopMedia(){
mpButtonKlick.release();
mpButtonKlick = null;
}
and when you call start() make sure to first call stopMedia();
stopMedia();
mpButtonKlick.start();
Try this one.
protected void onStop()
{
mediaPlayer.release();
mediaPlayer = null;
}

press home or back music stops

Hi In My Application I am playing one audio if i click back or home button that window should stop i am new to android please help me
final MediaPlayer mp = new MediaPlayer();
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(), Demovote2.class);
startActivity(nextScreen);
mp.start();
finish();
}
});
}
you should stop it on onpause method and replay it on onresume,
#Override
protected void onPause() {
mp.stop();
super.onPause();
}
#Override
public void onResume(){
// put your code here...
mp.start();
super.onPause();
}

onDestroy mediaplayer release

I want when I click on back button on the phone to close current activity and get back to menu and stop Media Player
But I get error: Unfortunately Weapons has stopped! upon clicking on back button
So how to fix that?
public class pushke extends Activity {
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
final MediaPlayer mp=MediaPlayer.create(this, R.raw.uzi);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{ }
#Override
public void onStartTrackingTouch(SeekBar arg0)
{ }
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mp.release();
}
}
Logcat:
1) I want when I click on back button on the phone to close current
activity and get back to menu and stop Media Player
1) What do you mean by menu? I mean application menu or device menu or notification bar etc.
2) But I get error: Unfortunately Weapons has stopped! upon clicking on
back button So how to fix that?
2)
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(mp!=null){
mp.stop();
mp.release();
mp = null;
}
}
EDIT:
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
mp=MediaPlayer.create(this, R.raw.uzi);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}
In On destroy before releasing media player please stop the media player

TextToSpeech API doesn't work when its called from OnStart

I'm using the TextToSpeech API in my code and it doesn't work when I try to call .speak() function from OnStart(), however it works when I call it from a button onClickListener(). Any idea why? Thank you.
public class TtsDemoActivity extends Activity {
private TextToSpeech mTts;
private OnClickListener buttonListener = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
PlaySound();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ttsdemo);
// Initialize Text To speech
mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
}
});
Button myButton = (Button)findViewById(R.id.buttontts1);
myButton.setOnClickListener(buttonListener);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
PlaySound();
}
protected void PlaySound()
{
String word = "Hello world";
mTts.speak(word, TextToSpeech.QUEUE_FLUSH, null);
}
You must wait until the TTS subsystem signals that it is ready: if it isn't ready when onStart is called, it will fail. If you are trying to speak as soon as it is ready call PlaySound from inside the OnInitListener:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ttsdemo);
// Initialize Text To speech
mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int arg0) {
if(arg0 == TextToSpeech.SUCCESS) PlaySound();
}
});
Button myButton = (Button)findViewById(R.id.buttontts1);
myButton.setOnClickListener(buttonListener);
}
Maybe I am blind, but in your onStart method, you aren't ever calling
PlaySound()
Like you are in
#Override
public void onClick(View arg0) {
PlaySound();
}

Categories

Resources