Multiple songs are playing, - java

Hello Every One I am trying to make music app in Android Studio. When I select a song in a recycler view, the song start playing in the new activity but when I go back to the songs list and select the new song both the songs start playing,I want that the previous song which was selected in the first place stop playing and new song start playing, How can I do it?
package com.recycler.hp.navigationbar;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
public class Revival_Activity extends Activity implements
OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener {
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
String editTextSongURL;
private MediaPlayer mediaPlayer;
private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
private final Handler handler = new Handler();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_revival_);
editTextSongURL=getIntent().getStringExtra("url");
initView();
}
/**
* This method initialise all the views in project
*/
#SuppressLint("ClickableViewAccessibility")
private void initView() {
buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
// editTextSongURL = getString(R.string.testsong_20_sec);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
/**
* Method which updates the SeekBar primary progress by current song playing position
*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.ButtonTestPlayPause) {
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource(editTextSongURL); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.pause);
} else {
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.play);
}
primarySeekBarProgressUpdater();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.SeekBarTestPlay) {
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if (mediaPlayer.isPlaying()) {
SeekBar sb = (SeekBar) v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
buttonPlayPause.setImageResource(R.drawable.play);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
seekBarProgress.setSecondaryProgress(percent);
}
}

It’s possible that you’re creating multiple media player objects during your selections in your recyclerview. Try creating a singleton instance of media player that’s shared throughout your app and call mediaplayer.release() and then recreate before playing a new song.

Related

if mediaplayer.pasue() is called before mediaplayer.start() , then music is not playing

i created two onClick methods for buttons Play and Pause but if tap on Pause first and then tap on Play button, The music is not playing. below is the code
package com.example.myaudio;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
public void playAudio(View view)
{
mediaPlayer.start();
}
public void pauseAudio(View view)
{
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(this,R.raw.mymusic);
}
}
As the MediaPlayer documentation says, the only states in which it is valid to call pause are Started, Paused, and PlaybackCompleted.
Calling pause when in some other state puts the MediaPlayer instance in an Error state, and trying to start the MediaPlayer when it is in an Error state will not work.
Bottom line: don't call methods on a MediaPlayer unless the player is in a state in which it is ok to call that method (as described by the documentation).

stop playing sound when another sound is playing in android studio

hello I use MediaPlayer for play sound in my project in android studio
when I click in a button and play sound , and when I click in another button that button play another sound , I want the first sound or another sound be stoped and just the last button that I clicked be played
I try this code but it not worked
package azad.broooska.fartfuns;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MusicFartActivity extends AppCompatActivity implements View.OnClickListener {
private CardView cardView1, cardView2, cardView3, cardView4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cardView1 = findViewById(R.id.card_music1);
cardView2 = findViewById(R.id.card_music2);
cardView3 = findViewById(R.id.card_music3);
cardView4 = findViewById(R.id.card_music4);
cardView1.setOnClickListener(this);
cardView2.setOnClickListener(this);
cardView3.setOnClickListener(this);
cardView4.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
final MediaPlayer s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
final MediaPlayer s2 = MediaPlayer.create(this, R.raw.fart_ballade);
final MediaPlayer s3 = MediaPlayer.create(this, R.raw.fart_uverture);
final MediaPlayer s4 = MediaPlayer.create(this, R.raw.farting_xmas);
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music2) {
s2.start();
s1.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music3) {
s3.start();
s2.stop();
s1.stop();
s4.stop();
} else {
Toast.makeText(this, "noThing", Toast.LENGTH_SHORT).show();
}
}
}
you are creating new instances of MediaPlayer each time something is clicked and assigning the variables to new objects; make s1,s2... class property;
MediaPlayer s1 ,s2,s3,s4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
//some code
s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
//assign the rest;
}
public void onClick(View view) {
int id = view.getId();
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
}
//rest of the code
}
Well, its seems like you don`t want to play very long sounds because you have names like
"fart_ballade" and "fart_uverture" in your code.
If your sounds are not very long it is better to work with the SoundPool class.
The MediaPlayer class sometimes can cause problems if you switch fast between sounds.
So if your sounds are not that long, you can try the SoundPool class.
Here you can learn more about the SoundPool class:
How to use SoundPool
I won`t write any code because SoundPool needs more than 5-6 lines of code to work properly.

Android: onBackPressed not being recognized

EDIT: Realized and solved the problem on my own. Thank you.
Please bear with me it's actually my first time using Android Studio and Stackoverflow. What I am trying to make is a music player, there are 2 activities. In the second activity when the user taps the play button, the music plays. If the user backs, the music will stop playing and go back to the first activity. Somehow on back pressed is not working. It's grayed out and it tells me that the Method is never used.
package com.radiantminds.radiantminds;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
}
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
}
You have to put it on an Activity, don't forget to call #Override
#Override
public void onBackPressed()
{
super.onBackPressed(); //if you want to do something new remove this line
}
The problem is that you have to place the onBackPressedMethod() outside, as follows :
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
#Override
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
//if you want to do the back action aswell, uncomment the following line
//super.onBackPressed();
}
Make sure the #override is there above the method and you don't declare the method twice.
other alternative is:
onKeyDown()
or add:
super.onBackPressed();
in the method onBackPressed (though i dont suggest it really)

Proximity Sensor- Silence call application

I am trying to build an android application that silences a call when a person waves his/her hand over the phone as it starts ringing/vibrating using the Proximity sensor.
I am new to android development.
I have tried to make the application check if the phone is in State-Rining. If it is, then the app checks if the value of the proximity sensor ==0 (near value). If the value for proximity sensor is 0, it implies that the sensor was cover during the ringing ad hence it should mute the call.
But it is still in ringing state.
I think the problem is that the ServiceReceiver only checks for the value of the proximity sensor just as the phone starts to ring. If the sensor value is not zero at that instant, the phone doesn't get silenced.
So how can I make it check for a change in value of proximity sensor throughout the ringing or incoming call such that as soon as the sensor value turns to zero, call is silenced
The first class "mainactivity" contains the code for proximity sensor.
package example.ringcheck;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
static TextView proxText;
SensorManager sm;
Sensor proxSensor;
static float proxValue = 8;
// static boolean muteCall = false;
private AudioManager amanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
proxSensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
proxText = (TextView) findViewById(R.id.ProximityTextView);
sm.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
proxText.setText(String.valueOf(event.values[0]));
proxValue = event.values[0];
Log.d("SENSOR VALUE", "********" + proxValue + "*******");
}
}
The second class "ServiceReceiver" contains the code for proximity sensor.
package example.ringcheck;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.telephony.TelephonyManager
import android.util.Log;
public class ServiceReceiver extends BroadcastReceiver {
private AudioManager amanager;
// static boolean isRinging = false;
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {
// isRinging = true;
if (MainActivity.proxValue == 0) {
amanager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
amanager.setRingerMode(0x00000000);
// isRinging = false;
}
Log.d("MPR", "Its Ringing");
}
}
}
Thanks in advance :-)
Instead of
amanager.setRingerMode(0x00000000);
Try
amanager.setStreamMute(AudioManager.STREAM_RING, true);

why wont my Gyroscope app in android fire off any events?

alright so I'm new to programming for android, and I think I did something wrong, but I don't know what. I've looked at 3 different tutorials and my code seems to look like theirs. Can anyone tell me what I'm doing wrong? here is my src (altered from a android nehe tutorial).
package cypri.games;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
/**
* The initial Android Activity, setting and initiating
* the OpenGL ES Renderer Class #see Lesson02.java
*
* #author Savas Ziplies (nea/INsanityDesign)
*/
public class DGearActivity extends Activity {
/** The OpenGL View */
private GLSurfaceView glSurface;
DGear dGear = new DGear();
private static final String TAG = "DEBUG";
SensorManager sensorManager;
private final SensorEventListener sensorListener = new SensorEventListener(){
public void onSensorChanged(SensorEvent se) {
if (se.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
dGear.playerX = se.values[0];
Log.v(TAG, "se.values[0] =" + se.values[0]);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
/**
* Initiate the OpenGL View and set our own
* Renderer (#see Lesson02.java)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
//Create an Instance with this Activity
glSurface = new GLSurfaceView(this);
//Set our own Renderer
glSurface.setRenderer(dGear);
//Set the GLSurface as View to this Activity
setContentView(glSurface);
}
/**
* Remember to resume the glSurface
*/
#Override
protected void onResume() {
Log.v(TAG, "or");
super.onResume();
glSurface.onResume();
sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
}
/**
* Also pause the glSurface
*/
#Override
protected void onPause() {
super.onPause();
glSurface.onPause();
Log.v(TAG, "op");
sensorManager.unregisterListener(sensorListener);
}
}
Are you running this in the emulator or on an actual device?
If you're running it on an actual device are you sure it has a gyroscope? There are lots of different sensor types and the gyroscope is only one of them. It could very well be one of the others.
Instead of only writing to the log if it's a gyroscope type, try writing the name of the se.sensor when that event fires. That way you'll at least know the event is firing.

Categories