android MediaPlayer setDataSource not grabbing a playable file - android

Hey I'm having trouble getting a stream to play from my localhost server (and also other websites with raw mp3 files). My code work for the site that is commented out so i assume it has something to
do with the server and not the java code.
public class MainActivity extends ActionBarActivity{
//static final String ANCHOR = "http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3";
static final String ANCHOR = "http://spintron.ddns.net/Random%20Access%20Memories/07%20-%20Touch.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = new MediaPlayer();
mp.setVolume(1, 1);
try{
mp.setDataSource(ANCHOR);
mp.prepareAsync();
}catch(Exception e){
e.printStackTrace();
}
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Toast.makeText(MainActivity.this,"Prepared",Toast.LENGTH_LONG).show();
mp.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

To play music file refer below code.
my res/raw folder contains options_music.wav music file.
// Play Music
MediaPlayer mp = new MediaPlayer();
AssetFileDescriptor descriptor;
try {
descriptor = getAssets().openFd("options_music.wav");
mp.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Log.e("Music", "Music Completed........");
mp.start();
}
});
} catch (Exception e) {
Log.e("ErrorMusic", "Cant Play Music File"+e);
}
For your url , make sure your it is properly url encoded and accessible from your mobile.

Related

How Can I stop mp3 player on menu

I create an items on menu to play mp3. But It couldnt stop. How could I stop mediaplayer when I click "stop" button. I want that clicking stop button must be stopp all playing mp3 on menu.
thanks...
public class DetailActivity extends AppCompatActivity {
Toolbar mToolbar;
ImageView mFlower;
TextView mDescription,mBaslik;
Button fab;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
mToolbar = findViewById(R.id.toolbar);
mToolbar.setTitle(getResources().getString(R.string.app_name));
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("MP3 --->");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.fon2);
mediaPlayer.start();
}
if (id == R.id.stop) {
mediaPlayer.stop();
mediaPlayer.release();
// mediaPlayer.onDestroy();
}
if (id == R.id.fav) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.fon2);
mediaPlayer.start();
}
if (id == R.id.yor) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.fon3);
mediaPlayer.start();
}
if (id == R.id.asd) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.fon1);
mediaPlayer.start();
}
return super.onOptionsItemSelected(item);
}
}
MediaPlayer mp;
AssetFileDescriptor descriptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout./////Your activity layout////);
if(mp != null){
if(mp.isPlaying()){
mp.stop();
}
}
try {
descriptor = getAssets().openFd("////the name of your song.mp3////"); // song should be in assets folder
} catch (IOException e) {
e.printStackTrace();
}
audioPlayer();
}
public void audioPlayer() {
//set up MediaPlayer
mp = new MediaPlayer();
try {
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
}
public void OnPlayPressed(View view){
if(mp.isPlaying()){
mp.pause();
}else{
mp.start();
}
}
public void OnStopPressed(View view){
mp.stop();
try {
descriptor = getAssets().openFd("////the name of your song.mp3////"); // song should be in assets folder
} catch (IOException e) {
e.printStackTrace();
}
audioPlayer();
}
Create 2 buttons, 1 for start/pause and one for stop. "OnPlayPressed" is the listener for the first button and "OnStopPressed" is the listener for the second button.
Feel free to mess with this code as long as you get the logic behind it.
Edit: In onStopPressed i reinitialise the descriptor so that you could once again press the "play" button and play your song again. This is not necessary though. You could just write "mp.stop();".
You have to declare the MediaPlayer object outside the method like this
MediaPlayer mediaplayer;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.foni) {
//MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.fon2);
mediaPlayer = MediaPlayer.create(this, R.raw.fon2);
mediaPlayer.start();
}
if (id == R.id.stop) {
//MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.stop();
}
if (id == R.id.fonb) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.fon1);
mediaPlayer.start();
}
if (id == R.id.fonu) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.fon3);
mediaPlayer.start();
}
return super.onOptionsItemSelected(item);
}

How to prebuffer VideoView A while another VideoView B is playing - Android

I am interested in being able to "prebuffer" VideoView A while VideoView B is playing. Is this possible?
I have two instances of a VideoView.
Only one VideoView will be displayed at a given time, taking up the entire screen of the phone.
The purpose is to reduce the "black screen" when switching from VideoView A and VideoView B.
The app plays a list of videos one after another.
Added Below Code on Jan 19, 2015
The code below grabs a reference to each Player's MediaPlayer. When MediaPlayer A begins rendering, MediaPlayer B will call stop(), release(), setDataSource(url), prepareAsync(). When MediaPlayer A completes, Media Player B will call start().
public class PrebufferingActivity extends Activity {
private VideoView player1;
private VideoView player2;
private MediaPlayer mediaPlayer1;
private MediaPlayer mediaPlayer2;
public static final String URL_1 = "sample1.mp4";
public static final String URL_2 = "sample2.mp4";
public boolean FIRST_TIME = true;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prebuffering);
player1 = (VideoView) findViewById(R.id.videoPlayer1);
player2 = (VideoView) findViewById(R.id.videoPlayer2);
player1.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
});
player2.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
});
player1.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer2.start();
// Toggle visibility. Player1 is completed. Hide Player1. Show Player2.
player2.setVisibility(View.VISIBLE);
player1.setVisibility(View.INVISIBLE);
}
});
player1.setOnInfoListener(new OnInfoListener(){
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
{
if(what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
{
mediaPlayer2.stop();
mediaPlayer2.release();
try {
mediaPlayer2.setDataSource(URL_2);
mediaPlayer2.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
});
player1.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer1 = mp;
if(FIRST_TIME == true) {
mediaPlayer1.start();
player1.requestFocus();
FIRST_TIME = false;
}
}
});
player2.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer1.start();
player1.requestFocus();
// Toggle visibility. Player2 is completed. Hide Player2. Show Player1.
player1.setVisibility(View.VISIBLE);
player2.setVisibility(View.INVISIBLE);
}
});
player2.setOnInfoListener(new OnInfoListener(){
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
{
if(what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
{
// Prepare Player 2
mediaPlayer1.stop();
mediaPlayer1.release();
try {
mediaPlayer1.setDataSource(PrebufferingActivity.URL_1);
mediaPlayer1.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
});
player2.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer2 = mp;
}
});
// Player 1
player1.setMediaController(new MediaController(this));
player1.setVideoURI(Uri.parse(URL_1));
// Player 2
player2.setMediaController(new MediaController(this));
player2.setVideoURI(Uri.parse(URL_2));
}
Assuming you are using MediaPlayer to handle the playback of your videos within your VideoView, you can use the prepareAsync() method to achive this. The prepareAsync() method essentially performs the same function as prepare(), which is used to buffer and prepare a video, except it can be done asynchronously in the background.
EDIT
I did something similiar but I actually used SurfaceView. To handle another stream, simply create another instance of MediaPlayer. The following example will create two instances of MediaPlayer and buffer the first video. After the first video is prepared, the second video will be asynchronously buffered. The first MediaPlayer is then bound to the SurfaceView and the first video is started. When the first video is finished playing, the corresponding instance of MediaPlayer is released, the secondary instance is attached, and the second video is automatically started. The following example code has been tested and works fine:
public class StreamingActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener
{
MediaPlayer mediaPlayerPrimary;
MediaPlayer mediaPlayerSecondary;
SurfaceHolder surfaceHolder;
SurfaceView surfaceView;
String videoSourcePrimary = "videoSourcePrimaryURL";
String videoSourceSecondary = "videoSourceSecondaryURL";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.streaming_activity_layout);
/** Create SurfaceView */
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder arg0)
{
try
{
/** Create MediaPlayer(s) */
mediaPlayerPrimary = new MediaPlayer();
mediaPlayerSecondary = new MediaPlayer();
/** Attach primary MediaPlayer to SurfaceView */
mediaPlayerPrimary.setDisplay(surfaceHolder);
/** Set sources */
mediaPlayerPrimary.setDataSource(videoSourcePrimary);
mediaPlayerSecondary.setDataSource(videoSourceSecondary);
/** Prepare MediaPlayer(s) */
mediaPlayerPrimary.prepare();
mediaPlayerSecondary.prepareAsync();
/** Set listeners */
mediaPlayerPrimary.setOnPreparedListener(this);
mediaPlayerPrimary.setOnCompletionListener(this);
mediaPlayerSecondary.setOnPreparedListener(this);
mediaPlayerSecondary.setOnCompletionListener(this);
/** Set audio stream type */
mediaPlayerPrimary.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayerSecondary.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0)
{
}
#Override
public void onPrepared(MediaPlayer mp)
{
if (mp == mediaPlayerPrimary)
{
/** First video ready, start playback */
mediaPlayerPrimary.start();
}
else if (mp == mediaPlayerSecondary)
{
/** Second video is ready */
}
}
#Override
public void onCompletion(MediaPlayer mp)
{
/** First video is completed, start second video */
mediaPlayerPrimary.release();
mediaPlayerSecondary.setDisplay(surfaceHolder);
mediaPlayerSecondary.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.streaming_activity_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}

Android native media player not firing onCompletion method

Native Android Media player does not invoke onCompletion method after the video has ran it's duration.
I have an Activity that plays a single video or a list of videos (m3u8 file). Video plays file as it should, I can use the media controller as well, however, when the video runs out, after a few seconds he starts a loop. onCompletion method doesn't activate unless the user clicks (or double taps) the fast forward option on media controler.
Is there a way to make the onComplete method activate automatically when the video runs out? (I've tried using the listener, doesn't work). Pointing out what I did wrong also works.
Here is the activity that handles video playing:
public class VideoActivity extends ActionBarActivity implements MediaPlayer.OnCompletionListener {
private static final String TAG = VideoActivity.class.getSimpleName();
private VideoView mVideoViewStream1;
ProgressDialog mDialog;
private String mURL;
private ChannelPlaylist mChannelPlaylist;
private int mIndex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
// Validate internet connection
if (!Util.isDeviceConnected(this)) {
FragmentManager fm = getSupportFragmentManager();
PopUpErrorFragment popupError = PopUpErrorFragment.newInstance(getString(R.string.errorInternetConnection));
popupError.show(fm, PopUpErrorFragment.TAG);
finish();
}
// Assign controls to their variable representations
mVideoViewStream1 = (VideoView) findViewById(R.id.vvVideo);
// Retrieve bundle data
Intent i = getIntent();
Bundle bundle = i.getExtras();
ChannelPlaylist channelPlaylist = bundle.getParcelable(KeyHelper.BUNDLE_CHANNEL_PLAYLIST);
if (channelPlaylist != null) {
this.mChannelPlaylist = channelPlaylist;
if (bundle.containsKey("index") && mIndex == 0) {
this.mIndex = bundle.getInt("index");
} else {
if (this.mIndex == 0) {
this.mIndex = this.mChannelPlaylist.getIndex();
}
}
this.mURL = this.mChannelPlaylist.getSchedule().get(mIndex).getStream_url();
} else {
this.mURL = bundle.getString("url");
}
progressDialog();
standardAndroidPlayer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.video, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/***************************** CLASS METHODS **************************************************/
/**
* Dismissess the dialog
*/
private void dismissDialog() {
if (this.mDialog != null) {
mDialog.dismiss();
}
}
/**
* Standard android player
*/
private void standardAndroidPlayer() {
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(mVideoViewStream1);
// Get the URL from String VideoURL
mVideoViewStream1.setMediaController(mediacontroller);
// Set media player completion listener
mVideoViewStream1.setOnCompletionListener(this);
mVideoViewStream1.setVideoURI(Uri.parse(this.mURL));
mVideoViewStream1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
//Log.i(TAG, "Duration = " + mVideoViewStream1.getDuration());
if (mp.isLooping()) mp.setLooping(false);
}
});
mVideoViewStream1.requestFocus();
mVideoViewStream1.start();
} catch (Exception e) {
dismissDialog();
Log.e(TAG, "Error" + e.getMessage());
e.printStackTrace();
}
dismissDialog();
}
#Override
public void onCompletion(MediaPlayer mp) {
this.mIndex++;
if (this.mIndex < mChannelPlaylist.getSchedule().size()) {
this.mURL = this.mChannelPlaylist.getSchedule().get(this.mIndex).getStream_url();
standardAndroidPlayer();
} else {
finish();
}
}
/**
* Creates a progress dialog
*/
private void progressDialog() {
// Create a progressbar
mDialog = new ProgressDialog(VideoActivity.this);
// Set progressbar title
mDialog.setTitle("Android Video Streaming Tutorial");
// Set progressbar message
mDialog.setMessage("Buffering...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
// Show progressbar
mDialog.show();
}
}
Edited:
Ok, for some strange reason, on mobile phone the method doesn't fire off, however when used on tablet, it does. I wasn't able to reproduce the effect on tablet and didn't have any success on the phone either. Does it have something to do with the versions of android? Since I didn't get any warnings about compatibility when writing the listener, I didn't think much about it.
Try this.
mVideoViewStream1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
finish();
}
});

ProgressBar does not reset after audio is finished

My ProgressBar does not reset after audio is done. I ask a question before on this and got it working but now just stopped working and not sure why it doesn't. Any help would be awesome.
All I want is it to chose a audio at random then play one and when finished you can press play again to listen to the same audio it chose at random.
Heres code:
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound01; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound02; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound03;
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player1.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
//When audio is done will change pause to play
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
//To update progress bar
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if(mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed(){
if (mp != null){
if(mp.isPlaying())
mp.stop();
mp.release();
}
//there is no reason to call super.finish(); here
//call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
You problem is mp.getDuration() is a milliseconds, which changes in each song. So don't use progressBar.setMax(mp.getDuration());. As it only works once for the very first song. Use progressBar.setMax(100); instead. Then use currentPosition= 100 * mp.getCurrentPosition() / mp.getDuration(); This should work fine.
Also don't forget adding progressBar.setProgress(0); when one song is finished or stop-button is clicked.
EDIT: Try resetting it inside of your completion listener. Scratch the setter then. Try using this:
Thread.sleep(1000);
currentPosition++;
Instead of this:
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
That is in your run() function. Then it will increment from 0 to total and you won't have to worry about getting or setting the currentposition, just the progress which is being done with the previous change below.
mp.setOnCompletionListener(new OnCompletionListener() {
//When audio is done will change pause to play
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
//Reset here
progressBar.setProgress(0);
}
});

Streaming MediaPlayer will not work with Samsung Galaxy S3

Streaming MediaPlayer not working on Samsung galaxy s3. Don't have device myself but getting reports of it not working. Also tried Remote Test Lab and does not work. I have tested on many other devices and all work excepted for s3. Any help would be awesome!
Code:
public class Radio extends Activity {
private MediaPlayer mp;
private ImageButton pauseicon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
Toast.makeText(this, "Just one moment please", Toast.LENGTH_LONG).show();
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
getActionBar().setDisplayHomeAsUpEnabled(true);
/**
* Play button click event plays a song and changes button to pause
* image pauses a song and changes button to play image
* */
String res = "http://************";
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
mp.start();
}
});
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if (mp.isPlaying()) {
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if (mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (mp != null) {
if (mp.isPlaying())
mp.stop();
mp.release();
}
// there is no reason to call super.finish(); here
// call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
This is what I do to get a streaming music to play, just tested this on a Samsung Galaxy SIII and it is working fine. The audio stream in this is a public university radio stream. But this should work with other online streams. Just make sure you enable the internet permissions in your manifest.
public class MainActivity extends Activity {
MediaPlayer mpMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
mpMediaPlayer = new MediaPlayer();
mpMediaPlayer.setDataSource("http://streams.tsc.usu.edu:8888");
mpMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpMediaPlayer.prepare();
mpMediaPlayer.start();
}catch(Exception e){
e.printStackTrace();
}
}
This might be a little late, but for those who are coming to this looking for this answer, one solution might be to implement the MediaPlayer.OnPreparedListener.
public class MyActivity extends Activity implements MediaPlayer.OnPreparedListener
MediaPlayer mpMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
try{
mpMediaPlayer = new MediaPlayer();
mpMediaPlayer.setDataSource("audio url");
mpMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpMediaPlayer.prepare();
mpMediaPlayer.setOnPreparedListener(this);
}catch(Exception e){
e.printStackTrace();
Log.e(TAG, "Error loading media");
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mpMediaPlayer.start();
}

Categories

Resources