I added in my app a simple feature that plays a simple sound when the button is clicked. It works fine with my Nexus 7 AVD, but when i run the code in Galaxy s3, it not displays any sound. The code is:
private void turnOnFlash() {
if(!isFlashOn) {
if(camera == null || parameters == null) {
return;
}
}
this.playSound();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isFlashOn = true;
}
and the playSound method:
private void playSound() {
mediaPlayer = MediaPlayer.create(this, R.raw.bar);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mediaPlayer.start(); //working on AVD, but do not work in S3.
}
Can someone help me fix this problem ? Thanks.
The problem is that the device sets the media volume to zero,
You can set media volume programmatically using this snippet of code :
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
This should help..
Related
hi i developed a simple app that should play a sound if a boolean is true and then another sound when it completes or just play the second sound if the boolean is false and it all works perfectly on the avd but when run on device it doesint let the first sound complete before jumping to the second
this is in the onCreate
setContentView(screen);//pl
if(msg==true) {//boolean set from other activity
playInfo();
}else if(msg==false){
playSound();
}
}
this is the play info method which starts to play but after a second it jumps to playsound method on the phone but works perfectly on avd
private void playInfo(){
mp = MediaPlayer.create(this, R.raw.msg);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
msg = false;
playSound();
}
});
}
this is the playsound method
private void playSound() {
mp = MediaPlayer.create(this, song);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playSound();//loop the sound
}
});
}
again this works perfect on emulator but not on a device why would they act differently and any ideas on how it would be resolved?
The activity was set to landscape mode on the device this caused the activity to be redrawn very quickly after launching so it started got destroyed and started again with the boolean set to false however on the emulator this does not happen it just draws the activity once in landscape mode solved the problem by using 2 different mediaplayers and just play the first short sound over the other rather than rework the code.
I am working on music player app where I am doing streaming of music using MediaPlayer. Streaming is working fine but now I want If user press back button of the activity then it should stop preparing & release media player immediately.
Currently when it is preparing and if activity is being destroyed then I am releasing the MediaPlayer like this but when it release it then it hangs the application & show ANR.
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer!=null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
I am initializing MediaPlayer like below
mediaPlayer = null;
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource("http://www.samisite.com/sound/cropShadesofGrayMonkees.mp3");
Now I want when it start preparing then on back press when I am releasing in onDestory then it should not hang the app & release the media player smoothly.
Please help me what is the best way to do this. Thanks in advance
mediaPlayer.prepareAsync();
Check the answer here. And the MediaPlayer State Diagram from android code.
Edit:
#TGMCians I showed him the provided link, So, if the playback is still not ready or preparing, he can not call stop() until it's called onPrepared. I'm not sure that onPrepared keep called after the app onDestroy called. So, The full snip I think is:
private boolean mPrepared = false;
private boolean mCancel = false;
public void onPrepared(MediaPlayer player){
mPrepared = true;
if(mCancel){
player.release();
mPrepared = false;
mCancel = false;
//nullify your MediaPlayer reference
mediaPlayer = null;
}
}
private void cancelMedia(){
mCancel = true;
}
#Override
protected void onDestroy() {
super.onDestroy();
cancelMedia();
if (mediaPlayer != null && mPrepared) {
mediaPlayer.stop();
mediaPlayer.release();
mPrepared = false;
mediaPlayer = null;
}
}
I am having an odd issue where my audio file sometimes plays and sometimes does not play. The catch is that when it decides to not play, the DDMS gives me an:
E/MediaPlayer﹕ Should have subtitle controller already set
Because this is one-to-one with the music not playing, I have determined that this is probably the issue...
If the music is not playing and I hit the volume button it begins to play.
If I wait about 30 seconds of no-play, it begins to start again (not looping).
Whats going on here? I am on KitKat using
player = new MediaPlayer();
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd("Theme.mp3");
} catch (IOException e) {
e.printStackTrace();
}
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
player.setLooping(true); //restart playback end reached
//player.setVolume(1, 1); //Set left and right volumes. Range is from 0.0 to 1.0
player.start(); //start play back
Looking at a previous discussion on StackOverflow, and the referenced Android commit where this was introduced, the code above might not completely initialize the MediaPlayer object.
The KitKat example code for media playback suggests that you should call:
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
immediately after you construct the MediaPlayer, and before you call its setDataSource method.
I had the same issue and I fixed it by adding the following right after instantiating MediaPlayer.
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (mp == mediaPlayer) {
mediaPlayer.start();
}
}
});
Previously I was implementing MediaPlayer.OnPreparedListener and overriding onPrepared() but it didn't work.
I hope this helps!
This should fix your problem (did for me): Replace the line that says "player.start()" following the rest of your code with an async callback like so:
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
This error is just a Log.e, not a real error. It shouldn't cause your player to not play, I'm guessing it's just because the player hadn't finished preparing when you try to call start().
E/MediaPlayer﹕ Should have subtitle controller already set
Its been a long time since I was working on this app. Here is what I ended up doing to get this to work. (Tested on KitKat and Lollipop). I think switching from MediaPlayer to APMediaPlayer was part of the trick.
#Override
public void onDestroy() {
if(player != null) {
player.release();
player = null;
}
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(player != null) {
player.start();
}
else {
player = new APMediaPlayer(this); //create new APMediaPlayer
player.setMediaFile("Theme.mp3"); //set the file (files are in data folder)
player.start(); //start play back
player.setLooping(true); //restart playback end reached
player.setVolume(1, 1); //Set left and right volumes. Range is from 0.0 to 1.0
}
}
#Override
public void onResume() {
super.onResume();
if(player != null) {
player.start();
}
}
set in manifest file may help you
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am trying to play audio from both the speakerphone and earpiece by having a button toggle between the two. The problem is that I am trying to default the audio to play from the earpiece, but nothing comes out. Then when I press the button to toggle to speakerphone, still no audio plays. I am playing from a local raw file.
I have android.permission.MODIFY_AUDIO_SETTINGS in the Manifest as well.
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
context = getActivity().getBaseContext();
am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(false);
am.setBluetoothScoOn(true);
speakerON = false;
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.buttonSpeaker:
if(!speakerON)//speaker off
{
speakerON = true;
am.setMode(AudioManager.MODE_NORMAL);
am.setSpeakerphoneOn(true);
am.setBluetoothScoOn(false);
speaker.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_lock_silent_mode_off, 0, 0, 0);
}
else
{
speakerON = false;
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(false);
am.setBluetoothScoOn(true);
speaker.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_lock_silent_mode, 0, 0, 0);
}
break;
}
}
Here is how I am setting up the MediaPlayer:
mediaPlayer = MediaPlayer.create(getActivity().getBaseContext(), R.raw.test_message);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mediaPlayer.start();
It turns out that I had set the mode wrong.
Here is the updated media player:
mediaPlayer = MediaPlayer.create(getActivity().getBaseContext(), R.raw.test_message);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.start();
And then I set the mode for the audio manager to :
context = getActivity().getBaseContext();
am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(false);
And then it worked. So make sure that the media player and audio manager are in the same mode.
I am trying to play a few music (wav format) files based on button clicks. I am unable to get MediaPlayer to work properly. Every time I try to instantiate an object of MediaPlayer class, it fails on create(). Before I post the code, here is a run-through of what I am doing:
1. A layout file that contains 2 buttons.
2. Those buttons are read and onClickListeners defined for them.
3. Depending on the button clicked, a function called playAudioFile(View) called which creates the MediaPlayer instance and plays the file. The code for playAudioFile(View) is as follows:
public void playAudioFile(View v) {
/*Steps:
* 1. Take in id of the button.
* 2. Using id, identify what file needs to be played.
* 3. Play file.
*/
String path_to_file = null; //this is the path to the file.
if(b01.getId() == ((Button)v).getId()) {
Log.v(this.toString(), "Button 01 pressed.");
path_to_file = "/sdcard/audio/temp1.wav";
} else if(b02.getId() == ((Button)v).getId()) {
Log.v(this.toString(), "Button02 pressed.");
path_to_file = "/sdcard/audio/temp2.wav";
}
path_to_file = "file://" + path_to_file;
Uri streamUri = Uri.parse(path_to_file);
Log.v(this.toString(), "Path of file = " + path_to_file);
MediaPlayer mp = MediaPlayer.create(this, streamUri);
if(mp == null) {
Log.v(this.toString(), "Create() on MediaPlayer failed.");
}
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
Log.v(this.toString(), "Illegal state exception thrown in start.");
}
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
I have gone through a lot of posts here on stackoverflow that detail solutions to the above problem. I am encountering this problem after having incorporated all the suggestions made therein. Any help is most welcome.
Thanks,
Sriram
I dont understand why you are trying to do
MediaPlayer mp = MediaPlayer.create(this, streamUri);
This is my implementation of my Player, Hope this will help you in some way:
MediaPlayer mp = new MediaPlayer();
setContentView(R.layout.player);
Intent intent = getIntent();
String path = "";
System.out.println("My Scheme : "+intent.getData().toString().substring(8));
if (intent.getData().getScheme().equals("video")) {
path = intent.getData().toString().substring(8);
System.out.println("Path : "+path);
if(path.endsWith(".mp3")) {
setContentView(R.layout.musicplayer);
setContentView(R.layout.controls);
Log.e("MusicPlayer", "Playing: " + path);
try {
Notification notification = new Notification(
R.drawable.playbackstart, path, System.currentTimeMillis());
nm.notify(NOTIFY_ID, notification);
mp.reset();
mp.setDataSource(path);
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
System.out.println("Hi i am at the End");
}
});
}catch {expression}
If I'm not wrong, you can't use onPrepare because mp.prepare() is called inside MediaPlayer.create(). The simpliest code can be something like this:
MediaPlayer mp = MediaPlayer.create(this, streamUri);
mp.start();
If you want something more elaborated, you can try this:
MediaPlayer mp = MediaPlayer.create(this, streamUri);
if(mp == null) {
Log.v(this.toString(), "Create() on MediaPlayer failed.");
} else {
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//here you should call the methods to release memory
mp.stop();
mp.release();
}
});
mp.start();
}
Tell me if it helped you.
PD: Is better if you use a device for testing rather than a simulator. Some classes don't work properly there (MediaPlayer can't reproduce video in simulators) and I don't remember if it supports audio.
As far as I understand your problem: You are calling the MediaPlayer.create(...) method, and it returns null, meaning the creation of a MediaPlayer instance failed. According to the accepted answer of this post MediaPlayer.create() always returns null it is due to a corrupted audio file.
I also have an issue, where the sound gets played but on rare occasions the create() method also returns null. I use sounds in a turn based game, after each turn a sound is played. I always call the create method, start the player and release it when it's done. That happens every turn and like once in 300 turns the create method returns null... So in my case it must be something else. In yours it could probably have something to do with the corruption of the mp3 file.