public void onRadioClick(View v) {
if (!isPLAYING) {
isPLAYING = true;
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(getString(R.string.audio_stream));
mp.prepare();
mp.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
} else {
isPLAYING = false;
stopPlaying();
}
}
private void stopPlaying() {
mp.release();
mp = null;
}
Answer from Hades on Stack Overflowpublic void onRadioClick(View v) {
if (!isPLAYING) {
isPLAYING = true;
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(getString(R.string.audio_stream));
mp.prepare();
mp.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
} else {
isPLAYING = false;
stopPlaying();
}
}
private void stopPlaying() {
mp.release();
mp = null;
}
The answer provided above provides synchronous fetching and playing, meaning currently executing thread will be blocked until prepare() is completed.
prepareAsync() can be used instead to "prepare" the stream asynchronously. You also will need to handle onPrepared() event to start playing.
mediaPlayer.setDataSource(URL here);
mediaPlayer.prepareAsync();
Add OnPrepared event handler:
mPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mPlayer.start();
}
});
Still, apparently there is no way to configure streaming buffer size. Frustrating...
android - How can I play a mp3 without download from the url? - Stack Overflow
android - Play audio from url one after other - Stack Overflow
[Feature Request] Play audio from URL
java - Simple audio player to play music using a URL built using MediaPlayer in Android - Code Review Stack Exchange
Videos
Look at these two tutorials, In these the .mp3 files are playing through web url,
Example of streaming mp3 mediafile from URL with Android MediaPlayer class
Play Mp3 file from a Url
Also if you want to play .mp3 file in background I think you have to use Service and AIDL for it,
Look at basic Android-Music Player demo MusicDroid - Audio Player Part II it describe how to use Service and AIDl for your Audio Player.
Thanks..
simple method to do this ::
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();
I'd like to make Tasker play audio directly from a url, this applies to a lot of programs/podcats and other long audios you may want to listen to while you drive/commute/walk/on the go.
I think the way Tasker implemented the "Music Play Dir" action is the right way, meaning that the action will trigger the audio and will require another action to stop it, rather than keep the task alive and get Tasker stuck.
Yes, there are a lot of apps that could help in this regard but because this is a quite simple action and the fact that Tasker shines above all other apps is circumstances. All the other phone setup before you start listening, for me, it always disappointing to set everything up with Tasker and then launch 3rd party software that does one simple action.
simple Media Player with streaming example.For xml part you need one button with id button1 and two images in your drawable folder with name button_pause and button_play and please don't forget to add the internet permission in your manifest.
public class MainActivity extends Activity {
private Button btn;
/**
* help to toggle between play and pause.
*/
private boolean playPause;
private MediaPlayer mediaPlayer;
/**
* remain false till media is not completed, inside OnCompletionListener make it true.
*/
private boolean intialStage = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn.setOnClickListener(pausePlay);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private OnClickListener pausePlay = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (!playPause) {
btn.setBackgroundResource(R.drawable.button_pause);
if (intialStage)
new Player()
.execute("http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3");
else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = true;
} else {
btn.setBackgroundResource(R.drawable.button_play);
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
playPause = false;
}
}
};
/**
* preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread.
* @author piyush
*
*/
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
intialStage = true;
playPause=false;
btn.setBackgroundResource(R.drawable.button_play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mediaPlayer.start();
intialStage = false;
}
public Player() {
progress = new ProgressDialog(MainActivity.this);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
this.progress.show();
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}
Android MediaPlayer doesn't support streaming of MP3 natively until 2.2. In older versions of the OS it appears to only stream 3GP natively. You can try the pocketjourney code, although it's old (there's a new version here) and I had trouble making it sticky โ it would stutter whenever it refilled the buffer.
The NPR News app for Android is open source and uses a local proxy server to handle MP3 streaming in versions of the OS before 2.2. You can see the relevant code in lines 199-216 (r94) here: http://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/PlaybackService.java?r=7cf2352b5c3c0fbcdc18a5a8c67d836577e7e8e3
And this is the StreamProxy class: http://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/StreamProxy.java?r=e4984187f45c39a54ea6c88f71197762dbe10e72
The NPR app is also still getting the "error (-38, 0)" sometimes while streaming. This may be a threading issue or a network change issue. Check the issue tracker for updates.
You can play a URL in just_audio like this:
final player = AudioPlayer();
await player.setUrl('https://example.com/song.mp3');
player.play();
player.pause();
player.seek(Duration(seconds: 143);
To add notification support, the easiest way is to add just_audio_background. You need to change the above code slightly so that instead of calling setUrl, you now do this:
await player.setAudioSource(AudioSource.uri(
'https://example.com/song.mp3',
tag: MediaItem(
id: 'Some unique ID',
title: 'Song title',
album: 'Song album',
artUri: Uri.parse('https://example.com/art.jpg'),
),
));
Now once that song starts playing, the supplied metadata will also be shown in the notification.
just_audio_background must also be initialised in your main:
Future<void> main() async {
await JustAudioBackground.init(/* See API for options */);
runApp(MyApp());
}
And don't forget to follow the platform-specific setup instructions for each plugin:
- just_audio
- just_audio_background
Note that just_audio_background uses the audio_service plugin under the hood, so if your app has more complex requirements, you could use that plugin directly.
If you have questions about how to build the actual UI, you can create a separate question on that, or you can look at the above two links because each plugin includes an example app which demonstrates how to link it all up in a UI.
Open AndroidManifest.xml file and enable internet permission ,usesCleartextTraffic
android\app\src\main\AndroidManifest.xml
Add following 2 lines for enabling internet permission and usesCleartextTraffic
