button4 = findViewById(R.id.button4);
musicSound = MediaPlayer.create(this, R.raw.music);
buttonClick(); }
private Button button4;
private MediaPlayer musicSound;
public void buttonClick() {
button4.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay(musicSound);
}
} ); }
public void soundPlay(MediaPlayer sound) {
{ sound.start();
sound.setLooping(true); }
buttonMusicStop = findViewById(R.id.buttonMusStop);
buttonClick2();}
private ImageButton buttonMusicStop;
public void buttonClick2() {
buttonMusicStop.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay2(musicSound);
}});}
public void soundPlay2(MediaPlayer sound) {
if (sound.isPlaying()) {
sound.pause();
} else {
sound.start();
sound.setLooping(true);
} }
Hello! I start music in my application, but when I minimize the application, the music does not stop. What do I need to write so that when the application is minimized and also when the screen is turned off, the music stops. Any help would be greatly appreciated!
Seem your app is playing in background. So create onResume and onStop to stop play and release resource, somethings look like this
onStop{
sound.stop();
sound.reset();
sound.release();
mediaplayer = null;
supper.onStop();
}
Related
Currently working on an app in Android Studio to play music from a live audio source. I got the play and pause button to work for certain url's such as this, which may only work either because it's http. However, when doing it with this link, which is live audio from a college radio station, it doesn't play anything (the static when the station is not on can't be heard in the app).
My code is below:
public class RadioSelection extends AppCompatActivity {
ImageView fm;
ImageView digital;
MediaPlayer mediaPlayer;
ImageView playPause;
String stream = "http://wmuc.umd.edu:8000/wmuc-hq";
boolean prepared = false;
boolean started = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_selection);
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
playPause = findViewById(R.id.play_pause);
fm = findViewById(R.id.fm);
digital = findViewById(R.id.digital);
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (started) {
started = false;
mediaPlayer.pause();
Toast.makeText(RadioSelection.this, "Paused", Toast.LENGTH_SHORT).show();
} else {
started = true;
mediaPlayer.start();
Toast.makeText(RadioSelection.this, "Playing", Toast.LENGTH_SHORT).show();
}
}
});
fm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
digital.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private class PlayerTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("It's prepared!");
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
#Override
protected void onPause() {
super.onPause();
if (started) {
mediaPlayer.pause();
}
}
#Override
protected void onResume() {
super.onResume();
if (started) {
mediaPlayer.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (prepared) {
mediaPlayer.release();
}
}
}
I feel like it has to do with the protocol but I'm not sure, and I don't really know of a way to test if it actually successfully connected to the audio source. I'd really appreciate any help.
I want to play 6 different sounds triggered by 6 different buttons in background, so that if the app is on background the sound keeps playing.
When one sound is already playing, pressing another button will stop it and play its own sound,
Tapping the same button 2K times it stops, 2K+1 times: starts again.. (K is a non-null integer)
All of the code is done and seems to be working correctly, except that the player stops after one and a half minute. (This is not because of low memory)
Can anyone please tell me what am I doing wrong?
public class PlayService extends Service {
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
int btnId = intent.getExtras().getInt("ID");
Toast.makeText(this, "onStart service" + btnId, Toast.LENGTH_SHORT).show();
selectResId(btnId);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_SHORT).show();
if (player != null) {
player.stop();
player.release();
}
player = null;
}
#Override
public void onLowMemory() {
super.onLowMemory();
Toast.makeText(this, "Low mem", Toast.LENGTH_SHORT).show();
}
private void selectResId(int resId){
switch (resId){
case 1: playMediaFromResource(R.raw.number_one);
case 2: playMediaFromResource(R.raw.number_two);
case 3: playMediaFromResource(R.raw.number_three);
case 4: playMediaFromResource(R.raw.number_four);
case 5: playMediaFromResource(R.raw.number_five);
case 6: playMediaFromResource(R.raw.number_six);
default: break;
}
}
private void playMediaFromResource(int resId) {
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + resId);
try {
player.setDataSource(getApplicationContext(), mediaPath);
player.setLooping(true);
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the MainActivity:
public class MainActivity extends AppCompatActivity {
private Button btnStart1;
private Button btnStart2;
private Button btnStart3;
private Button btnStart4;
private Button btnStart5;
private Button btnStart6;
private Intent intent;
private int previousID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
setOnClickListeners();
}
private void findViewsByIds() {
btnStart1 = findViewById(R.id.btn_start_1);
btnStart2 = findViewById(R.id.btn_start_2);
btnStart3 = findViewById(R.id.btn_start_3);
btnStart4 = findViewById(R.id.btn_start_4);
btnStart5 = findViewById(R.id.btn_start_5);
btnStart6 = findViewById(R.id.btn_start_6);
}
private void setOnClickListeners() {
btnStart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(1);
}
});
btnStart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(2);
}
});
btnStart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(3);
}
});
btnStart4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(4);
}
});
btnStart5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(5);
}
});
btnStart6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(6);
}
});
}
private void checkIntentState(int ID) {
if (intent == null) {
createNewIntent(ID);
} else {
stopService(intent);
intent = null;
if (ID != previousID) {
createNewIntent(ID);
}
}
}
private void createNewIntent(int ID) {
intent = new Intent(MainActivity.this, PlayService.class);
intent.putExtra("ID", ID);
startService(intent);
previousID = ID;
}
}
I want to answer to my own question just in case anyone else runs into the problem.
It turns out, that Android added some new features (restricted access to background resources for battery life improvement purposes since Oreo(i.e. Android 8.0+ || API level 26)).
As the documentation says:
"Apps that are running in the background now have limits on how freely they can access background services."
So, in this case we will need to use foreground services.
When I press the mute button on action bar that I have created it only stops the last sound being played and not all the sounds.
Also since the sound doesn't stop if I press the button(5-6 times) to play the sound and press mute on the same activity then go back and choose another activity and press that mute button the app crashes. Any ideas why?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
public void pb1(View view) {
mp = MediaPlayer.create(this, R.raw.sound1);
mp.start();
}
//inflates the menu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menunot, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sound:
mp.stop();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.stop();
mp.reset();
mp.release();
mp = null;
}
Just make an array list then stop all,
Take a look at the example below:
private static final int steps[] =
{R.raw.step_1, R.raw.step_2, R.raw.step_3, R.raw.step_4, R.raw.step_5, R.raw.step_6, R.raw.step_7, R.raw.step_8, R.raw.step_9, R.raw.step_10
};
private int i = 0;
private ArrayList<MediaPlayer> voices = new ArrayList<>(10);
private Button btnPlay;
private Button btnStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(i==10)i=0;
final MediaPlayer voice = MediaPlayer.create(MainActivity.this, steps[i++]);
voice.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (voice != null) {
voices.remove(voice);
voice.release();
}
}
});
voice.start();
voices.add(voice);
}
});
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int j = voices.size() - 1; j >= 0; j--) {
if (voices.get(j) != null) {
if (voices.get(j).isPlaying())
voices.get(j).stop();
voices.get(j).release();
voices.remove(j);
}
}
}
});
}
Hey please try the following solution,
SoundPool is a much better alternative for this purpose. I would caution strongly against instantiating multiple MediaPlayer instances as most systems do not have the resources to generate many parallel active instances. You will find on many device that hitting the button upwards of 5 times will cause a memory based crash.
As far as stopping all active streams, there is not baked-in function for this, but it's easy to accomplish in a manner to similar to your existing code. As a side note, there is an autoPause() method, which halts all streams, but it doesn't truly end their playback (as the method name insinuates). Here is a simple example to manage your audio streams:
//SoundPool initialization somewhere
SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
//Load your sound effect into the pool
int soundId = pool.load(...); //There are several versions of this, pick which fits your sound
List<Integer> streams = new ArrayList<Integer>();
Button item1 = (Button)findViewById(R.id.item1);
item1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int streamId = pool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
streams.add(streamId);
}
});
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Integer stream : streams) {
pool.stop(stream);
}
streams.clear();
}
});
It is much more memory efficient to manage a list of streamID values than MediaPlayer instances, and your users will thank you. Also, note that it is safe to call SoundPool.stop() even if the streamID is no longer valid, so you don't need to check for existing playback.
Happy coding :)
I am creating a piano app in android studio:
I have an on click listener for my play button which when pressed is supposed to make the record and play buttons invisible and the stop button visible while the recorded sounds are playing.
Play button
mBtn_Play.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mRecordingState = "Playing";
switchButtonVisibility();
for (final int sound: mListRecordedSounds )
{
if (mRecordingState == "Ready")
{//break out of loop when stop button is pressed
break;
}
else {
mSoundPool.play(sound, 1,1,1,0,1);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
});
}
Method for switching button visibility
private void switchButtonVisibility()
{
if (mRecordingState != "Ready")
{
mBtn_Stop.setVisibility(View.VISIBLE);
mBtn_Record.setVisibility(View.GONE);
mBtn_Play.setVisibility(View.GONE);
}
else
{
mBtn_Stop.setVisibility(View.GONE);
mBtn_Record.setVisibility(View.VISIBLE);
mBtn_Play.setVisibility(View.VISIBLE);
}
}
With the record and stop buttons, this works correctly
mBtn_Record.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mListRecordedSounds.clear();
mRecordingState = "Recording";
switchButtonVisibility();
}
});
mBtn_Stop.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mRecordingState = "Ready";
switchButtonVisibility();
}
});
For some strange reason it is executing the for loop first and playing the sounds before the switchButtonVisibility(); method changes which buttons are visible. This does not seem to make any sense as the method is above the loop. Is there any way to set it so the button visibility is changed first before the
loop is executed and the sounds are played?
Delay the execution, posting an event on the view. This will ensure, that the action would be performed as soon as the view is updated:
#Override
public void onClick(View v) {
mRecordingState = "Playing";
switchButtonVisibility();
mBtn_Play.post(new Runnable() {
#Override
public void run() {
for (final int sound : mListRecordedSounds ) {
// play the sound here
...
}
}
});
}
Hey guys I'm totally new to java, trying to finish my first project for college. I want to finish the code with setting OnCompletionListener to set the sound to null. So, it looks like this:
package com.example.alaiborys.newfuckingshit;
public class campfire extends AppCompatActivity {
MediaPlayer campfiresound;
int paused;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_campfire);
}
public void play(View view) {
if (campfiresound == null) {
campfiresound = MediaPlayer.create(this, R.raw.campfire);
campfiresound.start();
}
else if(!campfiresound.isPlaying())
{
campfiresound.seekTo(paused);
campfiresound.start();
}
}
public void stop(View view) {
campfiresound.release();
campfiresound = null;
}
public void pause(View view) {
campfiresound.pause();
paused = campfiresound.getCurrentPosition();
}
}
So, I want to add OnCompletionListener(): but have no idea where to put it and how to code it, any idea?
Well that is pretty easy...you have a media player object campfiresound
so you need to regisdter the interface OnCompletionListener
campfiresound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//toast...am done!!
}
});