Recently I started with Android.
I'm trying to do a small example to understand how the sound output with android.
To this I build me a program that plays an mp3 file, and while this playing can change the sound output to:
Internal Speaker
External Speaker
Headset
Earpiece
Is this possible?
I have part of the code done, but do not know how to jump from a sound output to another.
public class TestAudioActivity extends Activity {
private MediaPlayer mediaPlayer;
private ImageButton playButton;
private ImageButton pauseButton;
private ImageButton stopButton;
AudioManager audioManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeMediaPlayer();
playButton = (ImageButton) findViewById(R.id.playButton);
pauseButton = (ImageButton) findViewById(R.id.pauseButton);
stopButton = (ImageButton) findViewById(R.id.stopButton);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null)
mediaPlayer.start();
else
initializeMediaPlayer();
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
/** if (mediaPlayer != null)
mediaPlayer.pause(); */
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(false);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
});
}
private void initializeMediaPlayer() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("http://server3.pianosociety.com/protected/bach-bwv772-stahlbrand.mp3");
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// Mostramos mensaje en caso de error.
Toast.makeText(getApplicationContext(), "URL no encontrada", 2000);
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone help?
Thank you.
I have never played with media activities yet, but yes you can change your sound output while playing for example you can use
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
Related
i am trying to play media file with the following code using floating action button.
it works fine so far but it keeps playing even when i switch to another activity. I want to stop media player when back button pressed. Please help me...
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final MediaPlayer mp = new MediaPlayer();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("audio/sound.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onBackPressed() {
//here i want to stop media player with back button
super.onBackPressed();
}
Override OnDestroy and add below code:
#Override
public void onDestroy() {
if (mp != null) mp.release();
}
Can someone point out where I am going wrong with this? When I press the image button it always plays pinktestaudio first even if I did not press the corresponding button. I have to press the image button twice to hear the correct sound.This occurs when the page is first loaded, after the first time it seems fine but still something that shouldn't happen.
import android.content.Context;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class ColorPage extends AppCompatActivity {
Context context = this;
//MediaPlayer mpPurple, mpBlue, mpRed, mpGreen, mpYellow, mpPink;
MediaPlayer media = null;
//private static MediaPlayer media = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_page);
ImageButton pinkB = (ImageButton) findViewById(R.id.pinkButton);
ImageButton yellowB = (ImageButton) findViewById(R.id.yellowButton);
ImageButton purpleB = (ImageButton) findViewById(R.id.purpleButton);
ImageButton blueB = (ImageButton) findViewById(R.id.blueButton);
ImageButton greenB = (ImageButton) findViewById(R.id.greenButton);
ImageButton redB = (ImageButton) findViewById(R.id.redButton);
media = MediaPlayer.create(context, R.raw.purpleaudiotest);
purpleB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.purpleaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.blueaudiotest);
blueB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.blueaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.redaudiotest);
redB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.redaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.greenaudiotest);
greenB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.greenaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.yellowaudiotest);
yellowB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.yellowaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
pinkB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Updated: changing the start of the if statement(all of them) to as follows fixed the issue.
if (media != null) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
}
It always plays pinktestaudio because you have done
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
at the end, so media will always be initialized with pinktestaudio.
even after you click a different button because in every buttons OnClickListener you do
if(media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
}
on clicking any button for first time media.isPlaying() will always be false so
media = MediaPlayer.create(context, R.raw.some_audio_file);
will not be executed.
But when you click again media.isPlaying() is true and all goes well.
In onCreate 6 MediaPlayer instances are created. The last one is used in each of you listeners.
Take a look at your code after refactoring:
public class ColorPage extends AppCompatActivity implements View.OnClickListener {
MediaPlayer mMediaPlayer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_page);
ImageButton pinkB = (ImageButton) findViewById(R.id.pinkButton);
ImageButton yellowB = (ImageButton) findViewById(R.id.yellowButton);
ImageButton purpleB = (ImageButton) findViewById(R.id.purpleButton);
ImageButton blueB = (ImageButton) findViewById(R.id.blueButton);
ImageButton greenB = (ImageButton) findViewById(R.id.greenButton);
ImageButton redB = (ImageButton) findViewById(R.id.redButton);
pinkB.setOnClickListener(this);
yellowB.setOnClickListener(this);
purpleB.setOnClickListener(this);
blueB.setOnClickListener(this);
greenB.setOnClickListener(this);
redB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int audio;
switch (view.getId()) {
case R.id.pinkButton:
audio = R.raw.pinkaudiotest;
break;
case R.id.yellowButton:
audio = R.raw.yellowaudiotest;
break;
case R.id.purpleButton:
audio = R.raw.purpleaudiotest;
break;
case R.id.blueButton:
audio = R.raw.blueaudiotest;
break;
case R.id.greenButton:
audio = R.raw.greenaudiotest;
break;
case R.id.redButton:
audio = R.raw.redaudiotest;
break;
default:
audio = R.raw.purpleaudiotest;
}
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.release();
}
mMediaPlayer = MediaPlayer.create(getApplicationContext(), audio);
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Good luck!
This is because you have assigned the media variable a number of times and the last time it was assigned for pinkaudiotest so to solve your problem you have to assign the variable media inside the events. So it will be assigned only when a button is clicked.
`.
Here is what you are supposed to do using your own same code:
You have SIX lines that looks alike they are of the form of
media = MediaPlayer.create(context, R.raw.purpleaudiotest);
Cut those lines and paste them inside the onClick method of the corresponding Image Button for example. I am going to do the first one for you and repeat it for all SIX times.
purpleB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I AM ADDING IT HERE
media = MediaPlayer.create(context, R.raw.purpleaudiotest); //ADDED INSIDE oClick(View view)
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.purpleaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Repeat that for all SIX ImageButton and problem will be gone.
I'm using MediaPlayer for play a click sound when user clicks on a button. Sometimes the sound will play fine but other times it is too slow. For example first click is fine but second click is too slow.
Here is my code:
private MediaPlayer mClickSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mClickSound = MediaPlayer.create(this, R.raw.click);
}
#Override
public void onClick(View view) {
try {
if (mClickSound.isPlaying()) {
mClickSound.stop();
mClickSound.release();
mClickSound = MediaPlayer.create(this, R.raw.click);
}
mClickSound.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Try this:
mClickSound.reset();
AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.click);
if (afd == null) return;
mClickSound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mClickSound.start();
afd.close();
setDataSource is taken from here:
https://stackoverflow.com/a/20111291/6159609
The reset method is supposed to be faster.
Please try below code working fine for me...
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
Button btn;
MediaPlayer mClickSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
mClickSound = MediaPlayer.create(this, R.raw.click);
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickSound.isPlaying()) {
mClickSound.reset();
}
else {
mClickSound = MediaPlayer.create(this, R.raw.click);
mClickSound.start();
}
}
}
Hi every one i write a code to play fm radio waves. In my code there are a progressbar and two buttons one of them for play and another for stop. when i click play button it not happen. how can i solve this problem? or is there good suggest for me to play audio m3u8 files?
The code I'm using is:
public class Main extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://url.m3u8");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
I solve this problem by vitamio library. thanks
Try to call setOnPreparedListener() before prepareAsync() if you don't get onPrepared() callback.
According to the documentation, Android 4.0 and above doesn't support mp3 chunks. It supports only ts-files.
Furthermore, if your link hasn't .m3u8 in the end a MediaPlayer can't play it. Which tells that Content-Type: application/vnd.apple.mpegurl is abandoned. And you must have .m3u8 extension in the link.
In my project, I am playing music file in android media player by using the following code
MediaPlayer mPlayer = MediaPlayer.create(MyActivity.this, R.raw.myfile);
mPlayer.start();
the above is coded in the onclick of the play button.
I want to pause the playback by clicking the same button again.ie) single button for play/pause.
How shall i do this.
You could use simple if-check to handle the pausing. Try this:
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
Please try this::
final Button bPlay = (Button) findViewById(R.id.bPlay);
MediaPlayer song1 = MediaPlayer.create(tutorialFour.this, R.raw.fluet);
Button bStop = (Button) findViewById(R.id.bStop);
bPlay.setWidth(10);
song1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bPlay.setText("Play");
}
});
bPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
b = true;
if (bPlay.getText().equals("Play") && b == true) {
song1.start();
bPlay.setText("Pause");
b = false;
} else if (bPlay.getText().equals("Pause")) {
x = song1.getCurrentPosition();
song1.pause();
bPlay.setText("Resume");
Log.v("log", "" + x);
b = false;
} else if (bPlay.getText().equals("Resume") && b == true) {
song1.seekTo(x);
song1.start();
bPlay.setText("Pause");
b = false;
}
}
});
Inside the button click check for mediaPlayer.isPlaying(). This will return true if the media player is playing else false.
So now with this, flag value you can make a if statement and switch to play or pause like this,
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
} else {
mediaplayer.start();
}
}
});
Below code takes care of your play/pause button click event along with forward and backward buttons for forward and backward seek on the seekbar provided (which is synchronized with the media track). Currently it plays just ONE song. However, you can add to that. This is my first media player using mediaplayer class, so you might find it a bit primitive. However if you need you can also check out the VideoView examples. It's apparently easier with VideoView as the standard media console is already present in the form of pre-defined widgets. so that makes designing the player much easier.
package in.org.Test;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Toast;
public class Test12Activity extends Activity implements OnClickListener,Runnable {
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
private SeekBar seek;
MediaPlayer player = new MediaPlayer();
private ImageButton plus,minus;
ImageButton im;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton3);
player = MediaPlayer.create(this, R.raw.sound2);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton1);
seek = (SeekBar) findViewById(R.id.seekBar1);
seek.setVisibility(ProgressBar.VISIBLE);
seek.setProgress(0);
seek.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { int cu = player.getCurrentPosition(); player.seekTo(cu-5000); }});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {int cu = player.getCurrentPosition(); player.seekTo(cu+5000);}});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton1) {
if(player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.play);
}
else
{
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.pause);
}
}
}
#Override
public void run() {
int currentPosition= 0; String s;
int total = player.getDuration();
while (player!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek.setProgress(currentPosition);
}
}
}
MediaPlayer mpE = MediaPlayer.create(GuitarTuner.this, R.raw.test2 );
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mpE.isPlaying()) {
mpE.pause();
play.setBackgroundResource(R.drawable.play);
} else {
mpE.start();
play.setBackgroundResource(R.drawable.pause);
}
}
});
For pausing the Mediaplayer:
Mediaplayer.pause();
length = Mediaplayer.getCurrentPosition();
and for resuming the player from the position where it stopped lately is done by:
Mediaplayer.seekTo(length);
Mediaplayer.start();
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//the song was previously saved in the raw folder. The name of the song is mylife (it's an mp3 file)
final MediaPlayer mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.mylife);
// Play song
Button playButton = (Button) findViewById(R.id.play);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.start(); // no need to call prepare(); create() does that for you
}
});
// Pause song
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.pause();
}
});
// Stop song - when you stop a song, you can't play it again. First you need to prepare it.
Button stopButton = (Button) findViewById(R.id.stop);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.stop();
mMediaPlayer.prepareAsync();
}
});
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = button.getText().toString();
if (text.equals("play")){
mediaPlayer.start();
button.setText("pause"); //changing text
}
else if (text.equals("pause")){
mediaPlayer.pause();
button.setText("play"); //changing text
}
}
});
very simple solution. If mediaplayer is playing, display play button and pause the mediaplayer. If not playing, do the opposite.
playBtn.setOnClickListener(view -> {
//events on play buttons
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.play);
} else {
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.pause);
}
});