android Media Player stream more than 1 URL - java

I'm using mediaPlayer in my Android application to stream an MP3 url from online. Instead of just playing the 1 url, how can I stream 5 urls to play one after the other? here's my code
Uri myUri = Uri.parse("https://db.tt/9nBgouRf");
final MediaPlayer sdrPlayer = new MediaPlayer();
try {
sdrPlayer.setDataSource(this, myUri);
sdrPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
sdrPlayer.prepare(); //don't use prepareAsync for mp3 playback
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(channelx.this,
"Please turn on WiFi and try again", Toast.LENGTH_LONG).show();
}
play.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
sdrPlayer.start();
}
}
);

Just create a List to hold all of your URIs
Set up some class variables:
private int playlistPos = 0;
private List<Uri> myUris = new ArrayList<Uri>();
private MediaPlayer sdrPlayer = new MediaPlayer();
Set up a method for initialising the song:
public initSong(Uri myUri) {
try {
sdrPlayer.setDataSource(this, myUri);
sdrPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
sdrPlayer.prepare(); // don't use prepareAsync for mp3 playback
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(channelx.this,
"Please turn on WiFi and try again",
Toast.LENGTH_LONG).show();
}
}
Then in the onCreate()
myUris.add(Uri.parse("https://db.tt/9nBgouRf"));
// Add the others as well...
initSong(myUris.get(playlistPos);
sdrPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
playlistPos++;
initSong(myUris.get(playlistPos));
sdrPlayer.start(); // Start it as well if you wish
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sdrPlayer.start();
}
});

Related

how to make perfect media player in android with url type source

I have created a media player which get data from url. Url is based on volley response. I'm creating a MediaPlayer on item click so the onItemClick create every time a new MediaPlayer() . so i declared it in onCreate() but after it's giving too much errors .
below my code with MediaPlayer() declaration in onItemClick please help me anyone thanks
my motive:- i want to stop the playing song when another song is playing on item click
public class MusicsActivity extends AppCompatActivity{
private MediaPlayer mMediaPlayer;
}
public void OnItemClickActivity(int position,String video,String thumbnail,String thumbnails) {
String webUrl = "https://musicexample.com/";
Glide.with(this).load(webUrl + image).into(image);
text.setText(text);
Atext.setText(Atext);
mMediaPlayer = new MediaPlayer();
if (mMediaPlayer.isPlaying() && mMediaPlayer != null)
{
mMediaPlayer.stop();
mMediaPlayer.reset();;
mMediaPlayer.release();
mMediaPlayer = null;
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
togglePlayPause();
}
});
try {
mMediaPlayer.setDataSource(webUrl + src);
mMediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
To stop the Media Player without the risk of an Illegal State Exception, you must do
try {
mp.reset();
mp.prepare();
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}

Android MediaPlayer: How to stop if another audio file is being loaded?

I have a problem with the Android MediaPlayer. As soon as a new sound file is clicked by user input, the old one does not stop, so all audio files overlap.
I already tried common methods like MediaPlayer.stop(); and
MediaPlayer.release();
These methods always result in an app crash, although they are called in the correct order
public void Abspielen(String Datei) {
try {
AndreasPlayer = MediaPlayer.create(MainActivity.this, getResources().getIdentifier(Datei, "raw", getPackageName()));
AndreasPlayer.start();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Abspielen("filename");
}
I worked out the following solution:
public void Abspielen(String Datei) {
try {
stopKnopf = findViewById(R.id.fab2);
stopKnopf.show();
try {
if (AndreasPlayer.isPlaying()) {
AndreasPlayer.reset();
}
} catch (Exception ex) {
}
AndreasPlayer = MediaPlayer.create(MainActivity.this, getResources().getIdentifier(Datei, "raw", getPackageName()));
AndreasPlayer.start();
stopKnopf.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AndreasPlayer.reset();
stopKnopf.hide();
}
});
AndreasPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
AndreasPlayer.reset();
stopKnopf.hide();
}
});
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}

Livestream link MediaPlayer Android

I'm trying to get this stream to play:
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource("http://knhc-ice.streamguys1.com/live");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
But when the application runs it is giving me this error:
2019-03-17 17:01:05.035 5924-5924/com.example.android.c895 W/System.err: java.io.IOException: setDataSource failed.: status=0x80000000
I understand that the link that I am passing into the media player is just a single player, but I want that player to automatically play and be passed to the MediaPlayer. Is there anyway I can do this?
What I was able to figure out was put my MediaPlayer on Async Task(background thread) on my application.
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
b = (ImageButton) bottomSheet.findViewById(R.id.imageButton);
new PlayerTask().execute(s);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view)
{
if(started)
{
mediaPlayer.start();
}
}
});
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();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean)
{
super.onPostExecute(aBoolean);
mediaPlayer.start();
}
}
Since the codes are almost identically the same, could anyone answer why this works and not just on the main thread?

AssetFileDescriptor and Media Player #ISUESS

I m trying to play song by clicking a button in my application. There are two buttons in the application. Each button can play a different song. I allocated all those songs in Assets folder. There are total of two songs in the folder of Assets now.
public class AudioCollective implements MediaPlayer.OnPreparedListener, OnCompletionListener{
static String TAG = "AudioCollective====>";
Context mContext;
MediaPlayer mPlayer;
ArrayList<AssetFileDescriptor> array;
public AudioCollective(Context theContext){
mContext = theContext;
}
public void addSound(int SoundID){
array = new ArrayList<AssetFileDescriptor>();
AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(SoundID);
array.add(afd);
}
public void playSound() {
for (int i =0; i<array.size();i++) {
Log.i(TAG,"preparing audio " + array.get(i) );
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(array.get(i).getFileDescriptor());
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
}
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mPlayer != null) {
Log.d(TAG, "releasing audio now");
mPlayer.release();
mPlayer = null;
mediaPlayer.release();
//mediaPlayer = null;
}
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.i(TAG, "playing audio now");
mediaPlayer.start();
}
}
meanwhile in my MainActivity :
AudioCollective ac = new AudioCollective();
ac.addSounds(R.raw.na);
playButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
ac.playSound();
}
});
So, the problem is every time I clicked the button, the application play the two songs together instead of playing the required song. anyone can tell me why would this be happen?
Yes it because you are playing both of them at same in for loop.
Update your playSound() method pass value in it as argument.
To play first song pass 0 , To play second song pass 1 .
playSound(0) playSound(1)
public void playSound(int pos) {
Log.i(TAG,"preparing audio " + array.get(pos) );
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(array.get(pos).getFileDescriptor());
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
}
}

How to make a button play a sound as it launches another activity when pressed?

Current code:
MediaPlayer mp;
button1=(ImageButton)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Activity1.class);
startActivity(i);
}
});
So how would a button start a new activity and play a sound while doing so?
What I've tried: various methods like playSound( ); in the method.
It only plays the default android sound. I want a specific sound stored in the raw directory. So when the button get's pressed it launches both the intent to launch the activity as well as the specific sound.
Error:
When I try to put MediaPlayer mp; above the button, it states variable mp is already defined. I just need someone to append the activity launch code so that it will play the sound as well.
First you need to put a sound.mp3 in raw folder
MediaPlayer mp;
button1=(ImageButton)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mp = MediaPlayer.create(Music.this, R.raw.sound);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mp.start();
Intent i = new Intent(getApplicationContext(), Activity1.class);
startActivity(i);
}
});
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), Uri.parse(""));
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
// TODO Auto-generated method stub
player.start();
Intent i = new Intent(getApplicationContext(), Activity1.class);
startActivity(i);
}
});
Don't forget to release it : http://developer.android.com/reference/android/media/MediaPlayer.html#release%28%29
Mediaplayer mediaPlayer = MediaPlayer.create(this, R.raw.YOURMP3NAMEFILE);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(mp != null){
mp.release();
mediaPlayer = null;
Log.d(TAG, "release mediaplayer");
}
}
});
mediaPlayer.start();
launchSecondActivity();

Categories

Resources