I don't want to use AudioManager... Using the MediaPlayer API, my app
is not able to set the volume to desired level.
As it playes on previous level of volume which is set by Volume UP and Volume Down Key.
public class MainActivity extends AppCompatActivity {
protected static MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button next=(Button) findViewById(R.id.button);
mp=MediaPlayer.create(this,R.raw.m1);
mp.setVolume(0.02f,0.02f);
mp.start();
mp.setLooping(true);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
As mentioned in documentation:
"This API is recommended for balancing the output of audio streams within an application. Unless you are writing an application to control user settings, this API should be used in preference to setStreamVolume(int, int, int) which sets the volume of ALL streams of a particular type. "
https://developer.android.com/reference/android/media/MediaPlayer.html#setVolume(float,%20float)
You can however set a stream to your mediaplayer and let is play on
the desired stream like Music / Notification or Alarm which should
suffice the req.
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
Otherwise if you want to play some sound with certain level you have to use AudioManager API's to set a certain stream & set the volume of the stream and play the audio. This is a common practice.
Related
I am totally new to Android, and Java. I am designing an app that is constantly getting some input data(vital signals) and once abnormal reading is observed, ie heart rate < 50, the app will automatically send messages and make calls to one (or many) emergency contact(s). The tutorials I have found so far mentioning "auto send/call" are all about sending/calling within our own app using Intent, but the user still has to press the button to continue. Is there any way to do that?
The one I have now:
public class MainActivity extends AppCompatActivity {
private EditText phone;
private ImageButton call;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.number);
call = findViewById(R.id.call);
call.setOnClickListener(new View.OnClickListener(){
//set number
public void onClick(View v){
String phoneNumber = phone.getText().toString();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+phoneNumber));
startActivity(intent);
}
});
}
}
I have tried removing the listener so that it no longer waits for me to click the button to call:
phone = findViewById(R.id.number);
//Removed listener
String phoneNumber = phone.getText().toString();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+phoneNumber));
startActivity(intent);
But it turns out that once I launch the app, the app makes call directly even without typing in the number and of course call fail.
I think you need to use a Trigger Event. You can check this site for more information about it.
https://developer.android.com/reference/android/hardware/TriggerEvent
I have come across another error along my first app journey :) I want to play a sound when the app loads. Which is a .wav file. It lasts 2 seconds long yet it does not play when I run the app on my old Samsung S4. There is no errors within the IDE or anything I can see, I have checked if 'mp' has a value and it does. Looking around on posts most people have the problem that 'mp' is = null. Whereas mine has a value just no sound comes out of the phone... Again, any help is appreciated!
public class OpeningScreen extends Activity {
#Override
// create the screen state
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// connect the xml layout file
setContentView(R.layout.activity_opening_screen);
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
mp.start();
// create the on touch listener
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.opening_layout);
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// change the screen to a new state
Intent intent = new Intent(OpeningScreen.this, GameScreen.class);
// start the new activity
startActivity(intent);
// stop welcome sound (if still playing)
mp.stop();
return true;
}
});
}
}
public static MediaPlayer create(Context context, int resid) is a static method to create a MediaPlayer for a given resource id.
It means that by calling create you are creating a new instance of media player with no reference usage.
Try to change
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
to
final MediaPlayer mp = MediaPlayer.create(this, R.raw. welcome_message);
And the player should work.
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
http://developer.android.com/guide/topics/media/mediaplayer.html
Why do you use final?
You can play a mp3 with
MediaPlayer mp = MediaPlayer.create(OpeningScreen.this, R.raw.welcome_message);
mp.start();
Also stopping mediaplayer is better if you stop in onDestroy.
public void onDestroy() {
mp.stop();
super.onDestroy();
}
I`m trying to build an app, and one activity is "Radio" where I have a streaming online Radio. If i click play, everything works fine, it plays, when I click stop, it stops. But the problem is when I change the activity, ex: from "Radio" to "Home", or "Contact" and come back to "Radio", radio still runs, and if I want to stop it, doesn't work. but if I hit play, the music duplicates and therefore I have the same radio open two times. It looks like the application doesn't know that Radio already runs. Do I need a service object, or what? If I need a service can someone explain me where exactly in the code should I implement it? Here is my Java code:
public class radioActivity extends AppCompatActivity {
int length;
Button b1;
private Button Button1;
private Button Button2;
private String STREAM_URL = "http://192.99.35.93:6370/;stream.mp3";
private MediaPlayer mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
Button button1 = (Button) findViewById(R.id.buttonpredica1);
Button button2 = (Button) findViewById(R.id.buttonpredica2);
mPlayer = new MediaPlayer();
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
WifiManager.WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wifiLock.acquire();
wifiLock.release();
button1.setOnClickListener(new View.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 mPlayer) {
mPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.stop();
}
});
Your MediaPlayer is being created each time you click on start button, so multiple instance of MediaPlayer are playing Radio
If you dont want your MediaPlayer to be running when you switch Activities you can call mPlayer.stop(); in onPause() of your Activity
You can have a couple of options here, one would be to create a Singleton Instance of your MediaPlayer object so when you go to and fro from your RadioActivity, the same instance of the MediaPlayer Object is being used which will help you control the MediaPlayer
Singleton design pattern in Java. Singleton Pattern says that just"define a class that has only one instance and provides a global point of access to it". In other words, a class must ensure that only single instance should be created and single object can be used by all other classes.
Here in my MainActivity.java I have an object MediaPlayer, which plays a sound when you click playB button and pause by pressing pauseB. Everything is working fine. But if you re-open the app and click pauseB, the sound continues to play. How to fix it? How to catch the current playing MediaPlayer?
public class MainActivity extends ActionBarActivity {
Button playB;
Button pauseB;
Context c;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button playB = (Button) findViewById(R.id.playB);
Button pauseB = (Button) findViewById(R.id.pauseB);
mp = mp.create(this, R.raw.fawaid_1);
playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
pauseB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.pause();
}
});
}
}
when you re-open the app, onCreate is called again, hence you have a new MediaPlayer object, and from that moment, play and pause buttons will control that new player object instead of a previous one. That's why your pause button will have no effect on the sound that started BEFORE you minimized the app. And if you press play button now, you will have two sounds playing at the same time
one way to overcome this, is to check if media player has already been initialized:
if(mp==null)
mp = MediaPlayer.create(this, R.raw.fawaid_1);
It is advisable to use Service with AIDL in developing music player.
Reasons.
You can retain the control again once you go back in your activity.
It is easy to perform an inter process communication.
Here is a simple music Player that runs on the Background, Music Player
The song I used in this music player is Owned by SnowFlakes
I want the background music to repeat as long as the user stays in a particular screen. Is there a function in the MediaPlayer class that allows you to do the above task?
button1.setOnClickListener(new View.OnClickListener() {
#Overridepublic void onClick(View v) {
Intent intent = new Intent(context,kids_quiz.class);
startActivity(intent);
player=MediaPlayer.create(Games.this,R.raw.macdonald);
player.start();
}
});
Just start it when you are in that Activity, setLooping to true, and when the user leaves the screen destroy the mediaPlayer in Activity.onDestroy(and maybe onPause depending on what you want to accomplish) method.
Remember it is important to destroy a mediaPlayer when you're done with it as it consumes a lot of resources.