I have done the below code for running a music in background of activity, using asyncTask.
public class BackgroundSound extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params)
{ MediaPlayer player = MediaPlayer.create(BiographyActivity.this, R.raw.test_cbr);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
return null; }
}
#Override
protected void onResume()
{ super.onResume();
mBackgroundSound.execute(null); }
#Override
protected void onPause()
{ super.onPause();
mBackgroundSound.cancel(true); }
But its showing error for execute method inside onResume:
The method execute(Void[]) is ambiguous for the type BiographyActivity.BackgroundSound
I would strongly recommend not use async task for playing background music, instead you can use prepareAsync method from media player class which will itself load music in background.
Here is my implementation:
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
public class BiographyActivity extends Activity implements OnPreparedListener {
private MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media_player_activity);
}
#Override
protected void onResume() {
super.onResume();
final AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.test);
try {
releaseMediaPlayer();
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync();
afd.close();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.release();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
}
It means that View[] is ambiguous, Try execute(Void[3]) or execute();
Related
I'm creating a music player app in Android and I'm trying to set up the MediaPlayer as a service so that it persists across all Activities/Fragments. The service code:
public class PlayerService extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
}
public void LoadUrl(String url){
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//mediaPlayer.start();
Play(mediaPlayer);
}
public void Play(MediaPlayer player) {
player.start();
}
public void Pause(MediaPlayer player) {
player.pause();
}
}
and the MainActivity:
public class MainActivity extends AppCompatActivity {
PlayerService playerService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
} else {
playerService = new PlayerService();
Intent startPlayer = new Intent(this, PlayerService.class);
startService(startPlayer);
....
When MainActivity is started, it launches the service, however, when I try to load a Url into the MediaPlayer with:
playerService.LoadUrl(feedItem.getAudioUrl());
I get an exception saying that mediaPlayer in the Service is null. How can I make sure that the mediaPlayer is retained?
You are trying to start the service using startService without onStartCommand in service, without which the sevice won't start. So your media player won't get initialized
I put one song into an app (tabhost) and I have progress bar, play button, stop button, loop button.
The function I want is:
when user plays the music, the progress bar starts to run from "0"
when user presses stop, the progress bar stops at where it was, waits for the user to press play again, and then continues where it left off
I might change the button name to "pause" later, but this is the function I need right now.
Right now, 2 issues:
When stop is pressed, the progress bar returns to "0", but the music resumes playing from where it left off (music not playing from very beginning)
The progress bar runs faster than desired; it runs to the end before the music ending.
Here is my code, hope someone could help thank you so much:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import java.util.logging.LogRecord;
public class TabMusicActivity extends Activity {
MediaPlayer mediaPlayer;
private boolean playing = false;
private ProgressBar progressBar;
private Handler handler = new Handler();
int progress = 0;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
final ImageButton buttonStart = (ImageButton)findViewById(R.id.buttonStart);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!playing) {
playing = true;
buttonStart.setImageResource(R.drawable.music_stop_button);
Uri path = Uri.parse("android.resource://"+getPackageName()+"/"+ R.raw.bashibafo);
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(TabMusicActivity.this, path);
}
if (mediaPlayer != null) {
mediaPlayer.start();
process();
}
}
else {
playing = false;
buttonStart.setImageResource(R.drawable.button_play);
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
}
});
ImageButton buttonLoop = (ImageButton)findViewById(R.id.buttonLoop);
buttonLoop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.setLooping(true);
}
});
}
private void process (){
progressBar.setProgress(0);
progress = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progress < 100){
progress = doWork();
try{
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post( new Runnable() {
#Override
public void run() {
progressBar.setProgress(progress);
}
});
}
}
}).start();
}
private int doWork(){
progress++;
if (progress < 100){
return progress;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 100;
}
#Override
protected void onDestroy() {
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
super.onDestroy();
}
}
I used this code for playing music
if (player != null)
{
player.seekTo(length);
player.start();
}
else
{
player = MediaPlayer.create(context, Uri.fromFile(new File(url)));
seek_bar.setMax(player.getDuration());
seek_bar.setProgress(player.getCurrentPosition());
player.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
player.reset();
player.release();
player = null;
seekHandler.removeCallbacks(run);
seek_bar.setProgress(0);
if (recieveOrSend.equals("send"))
{
holder.iv_audio_pause_send.setVisibility(View.INVISIBLE);
holder.iv_audio_play_send.setVisibility(View.VISIBLE);
}
else
{
holder.iv_audio_pause_recieve.setVisibility(View.INVISIBLE);
holder.iv_audio_play_recieve.setVisibility(View.VISIBLE);
}
}
});
// player.prepare();
player.start();
}
seekUpdation();
Methods--
Runnable run = new Runnable()
{
#Override
public void run()
{
seekUpdation();
}
};
public void seekUpdation()
{
seek_bar.setProgress(player.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}
private void pausePlayer()
{
try
{
if (player != null)
{
player.pause();
length = player.getCurrentPosition();
seekHandler.removeCallbacks(run);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Below is my Code :
package com.example.videoplayer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
public class VideoPlayerActivity extends Activity {
String TAG = "com.example.VideoPlayer";
ProgressDialog progDailog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
final VideoView videoView = (VideoView) findViewById(R.id.videoView1);
videoView.setVideoPath("http://www.ebookfrenzy.com/android_book/movie.mp4");
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setOnPreparedListener(new
MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
progDailog.dismiss();
Log.i(TAG, "Duration = " + videoView.getDuration());
}
});
videoView.start();
progDailog = ProgressDialog.show(this, "Please wait ...", "Retrieving data ...", `enter code here`true);
}
#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_player, menu);
return true;
}
}
Check out this :
Play http videos in VideoView
This is my code :
public static void getVideoFromHttp(String urlPath) {
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(mContext);
mediacontroller.setAnchorView(mVideoview);
// Get the URL from String VideoURL
Uri mVideo = Uri.parse(urlPath);
mVideoview.setMediaController(mediacontroller);
mVideoview.setVideoURI(mVideo);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
mVideoview.requestFocus();
mVideoview.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
mVideoview.start();
}
});
mVideoview.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
}
});
}
Thanks
Don't do everything in the UI thread because it takes a lot of time. Do everything in AsyncTask and things will work out fine.
For beginners, this link describes how could you do it in AsyncTask.
Define a class which extends the AsyncTask:
public class BackgroundAsyncTask extends AsyncTask<String, Uri, Void> {
Integer track = 0;
ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(PlayVideo.this);
dialog.setMessage("Loading, Please Wait...");
dialog.setCancelable(true);
dialog.show();
}
protected void onProgressUpdate(final Uri... uri) {
try {
media=new MediaController(PlayVideo.this);
video.setMediaController(media);
media.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
// next button clicked
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
media.show(10000);
video.setVideoURI(uri[0]);
video.requestFocus();
video.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer arg0) {
video.start();
dialog.dismiss();
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... params) {
try {
Uri uri = Uri.parse(params[0]);
publishProgress(uri);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Then, in the onCreate() method, just call the execute() method of this BackgroundAsynchTask:
video = (VideoView) findViewById(R.id.video);
new BackgroundAsyncTask().execute("link-to-the-video");
I implemented everything I've found here, but my service is not starting yet.
What I need to do is to start playing a radio station when the user clicks on a button, and only stop it when he clicks it again. I don't want the radio to be stopped if the application get closed.
When I test the code I'm sending, nothing happens.
Manifest:
<service
android:name=".RadioService"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:exported="false"
>
</service>
Service Code:
package com.po.portelaonline.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class RadioService extends Service {
Player player;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate(){
player = new Player();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy(){
player.stopThread();
}
}
Player class code:
package com.po.portelaonline.service;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import com.po.portelaonline.classes.Util;
class Player extends Thread {
volatile boolean running = true;
#Override
public void run() {
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(Util.getRadioUrl());
player.setOnPreparedListener(oplPlayer);
player.prepareAsync();
while (running) {
Player.sleep(500);
}
player.release();
player = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopThread() {
running = false;
}
OnPreparedListener oplPlayer = new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
};
}
And I'm calling this way:
Intent i = new Intent(getApplicationContext(), RadioService.class);
if(getApplicationContext().startService(i) == null){
findViewById(R.id.btnPlayStop).setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.stop));
}else{
getApplicationContext().stopService(i);
findViewById(R.id.btnPlayStop).setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.play));
}
Try this code for service class.
You don't need to create MediaPlayer object in separate thread. player.prepareAsync(); is already asynchronous.
EDIT:
The path to the RadioService class into the AndroidManifest.xml should be absolute: android:name="com.po.portelaonline.service.RadioService"
public class RadioService extends Service implements OnPreparedListener, OnErrorListener{
MediaPlayer mPlayer;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startPlayer();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate(){
initMediaPlayer();
}
private void initMediaPlayer () {
mPlayer = new MediaPlayer();
mPlayer.setOnPreparedListener(this);
mPlayer.setOnErrorListener(this);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
}
private void startPlayer(){
player.setDataSource(Util.getRadioUrl());
player.prepareAsync();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy(){
mPlayer.release();
}
#Override
public void onPrepared (MediaPlayer mp) {
mp.start();
}
#Override
public boolean onError (MediaPlayer mp, int what, int extra) {
Log.e("RadioService OnError", "what="+what+" extra="+extra);
return false;
}
}
i guess it should be
if(getApplicationContext().startService(i) != null)
instead of if(getApplicationContext().startService(i) == null)
You are immediately stopping the service after you start it.
I want to use MediaPlayer android, using this code, but I get an error, there's a way to fix this code, or can anyone bring me a better example for this?
try {
MediaPlayer player = new MediaPlayer();
player.setDataSource("/LFP/res/raw/Allen.mp3");
player.prepare();
player.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.MotionEvent;
import android.widget.MediaController;
import android.widget.TextView;
import java.io.IOException;
public class AudioPlayer extends Activity implements OnPreparedListener,
MediaController.MediaPlayerControl{
private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);
((TextView)findViewById(R.id.now_playing_text)).setText(audioFile);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return false;
}
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
}
This worked fine for me.Hope it works for you also.
use
mediaplayer.prepareAsync()
and
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
instead it
Here I am keeping my audio file in asset. Following code works,
MediaPlayer mp= new MediaPlayer();
AssetFileDescriptor afd = null;
try {
afd =getActivity().getBaseContext().getAssets().openFd("myAudio.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (IOException e) {
e.printStackTrace();
}