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();
}
Related
I have a image button and video url. I want that video play when user onClick image button.I want that video played on same activity if that video stream is over then I have to return to same activity.
VideoView videoView;
ImageView btnWatchVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotions_feed);
btnWatchVideo = (ImageView) findViewById(R.id.btnWatchVideo);
videoView = (VideoView) findViewById(R.id.ltVideoUrl);
String path1 = "https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v";
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri uri = Uri.parse(path1);
videoView.setMediaController(mc);
videoView.setVideoURI(uri);
btnWatchVideo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
videoView.start();
}
});
This code is not working. Can any one suggest me how to do that.
Try using these two onCreate methods for the two Activities.
Video Vewing Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
videoView = (VideoView) findViewById(R.id.ltVideoUrl);
String path1 = "https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v";
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri uri = Uri.parse(path1);
videoView.setMediaController(mc);
videoView.setVideoURI(uri);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videoView.start();
}
});}
Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnWatchVideo = (ImageView) findViewById(R.id.btnWatchVideo);
btnWatchVideo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, VideoActivity.class));
}
});}
Try following the MediaPlayer tutorials on developer.android.com:
https://developer.android.com/guide/topics/media/mediaplayer.html
You need to change your code like this
package com.mobileappdev.spotstvhdlivestreamcric.activites;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.mobileappdev.spotstvhdlivestreamcric.R;
import com.mobileappdev.spotstvhdlivestreamcric.mediaplayer.ResizeSurfaceView;
import com.mobileappdev.spotstvhdlivestreamcric.mediaplayer.VideoControllerView;
import java.io.IOException;
public class MediaPlayerActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControlListener, MediaPlayer.OnVideoSizeChangedListener, MediaPlayer.OnCompletionListener {
private final static String TAG = MediaPlayerActivity.class.getSimpleName();
private ResizeSurfaceView mVideoSurface;
private MediaPlayer mMediaPlayer;
private VideoControllerView controller;
private int mVideoWidth;
private int mVideoHeight;
private View mContentView;
private View mLoadingView;
private boolean mIsComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
getSupportActionBar().hide();
mVideoSurface = (ResizeSurfaceView) findViewById(R.id.videoSurface);
mContentView = findViewById(R.id.video_container);
mLoadingView = findViewById(R.id.loading);
SurfaceHolder videoHolder = mVideoSurface.getHolder();
videoHolder.addCallback(this);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnVideoSizeChangedListener(this);
//(FrameLayout) findViewById(R.id.videoSurfaceContainer)
controller = new VideoControllerView.Builder(this, this)
.withVideoTitle("ADD VIDEO TITLE")
.withVideoSurfaceView(mVideoSurface)//to enable toggle display controller view
.canControlBrightness(true)
.canControlVolume(true)
.canSeekVideo(true)
.exitIcon(R.drawable.video_top_back)
.pauseIcon(R.drawable.ic_media_pause)
.playIcon(R.drawable.ic_media_play)
.shrinkIcon(R.drawable.ic_media_fullscreen_shrink)
.stretchIcon(R.drawable.ic_media_fullscreen_stretch)
.build((FrameLayout) findViewById(R.id.videoSurfaceContainer));//layout container that hold video play view
mLoadingView.setVisibility(View.VISIBLE);
try {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(this, Uri.parse("https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v"));
// mMediaPlayer.setDataSource(this, Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mVideoSurface.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
controller.toggleControllerView();
return false;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// controller.show();
return false;
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mVideoHeight = mp.getVideoHeight();
mVideoWidth = mp.getVideoWidth();
if (mVideoHeight > 0 && mVideoWidth > 0)
mVideoSurface.adjustSize(mContentView.getWidth(), mContentView.getHeight(), mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mVideoWidth > 0 && mVideoHeight > 0)
mVideoSurface.adjustSize(getDeviceWidth(this), getDeviceHeight(this), mVideoSurface.getWidth(), mVideoSurface.getHeight());
}
private void resetPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public static int getDeviceWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(mDisplayMetrics);
return mDisplayMetrics.widthPixels;
}
public static int getDeviceHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(mDisplayMetrics);
return mDisplayMetrics.heightPixels;
}
// Implement SurfaceHolder.Callback
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepareAsync();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
resetPlayer();
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
#Override
public void onPrepared(MediaPlayer mp) {
//setup video controller view
mLoadingView.setVisibility(View.GONE);
mVideoSurface.setVisibility(View.VISIBLE);
mMediaPlayer.start();
mIsComplete = false;
}
// End MediaPlayer.OnPreparedListener
/**
* Implement VideoMediaController.MediaPlayerControl
*/
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if (null != mMediaPlayer)
return mMediaPlayer.getCurrentPosition();
else
return 0;
}
#Override
public int getDuration() {
if (null != mMediaPlayer)
return mMediaPlayer.getDuration();
else
return 0;
}
#Override
public boolean isPlaying() {
if (null != mMediaPlayer)
return mMediaPlayer.isPlaying();
else
return false;
}
#Override
public boolean isComplete() {
return mIsComplete;
}
#Override
public void pause() {
if (null != mMediaPlayer) {
mMediaPlayer.pause();
}
}
#Override
public void seekTo(int i) {
if (null != mMediaPlayer) {
mMediaPlayer.seekTo(i);
}
}
#Override
public void start() {
if (null != mMediaPlayer) {
mMediaPlayer.start();
mIsComplete = false;
}
}
#Override
public boolean isFullScreen() {
return getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ? true : false;
}
#Override
public void toggleFullScreen() {
if (isFullScreen()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
#Override
public void exit() {
resetPlayer();
finish();
}
#Override
public void onCompletion(MediaPlayer mp) {
mIsComplete = true;
}
}
Your video is playing now.
I have created android app to stream online radio station and I want to run it in background using service.How to create service to run media player in background?
Here is source code of the application:
public class MainActivity extends AppCompatActivity
{
private ImageButton buttonPlay,buttonStop,buttonPause;
private String STREAM_URL = "http://178.149.86.162:8000/";
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);
buttonStop = (ImageButton) findViewById(R.id.buttonStopPlay);
buttonPause = (ImageButton) findViewById(R.id.buttonPause);
mPlayer = new MediaPlayer();
buttonPlay.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
mPlayer.reset();
mPlayer.setDataSource(STREAM_URL);
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
startService();
}
});
buttonStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mPlayer.stop();
stopService();
}
});
buttonPause.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mPlayer.pause();
stopService();
}
});
playbackServiceIntent = new Intent(this, BackgroundService.class);
}
private void startService()
{
startService(new Intent(MainActivity.this,BackgroundService.class));
}
private void stopService()
{
stopService(new Intent(MainActivity.this,BackgroundService.class));
}
}
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL = "http://178.149.86.162:8000/";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
mediaPlayer = new MediaPlayer();
try
{
mediaPlayer.setDataSource(STREAM_URL);
} catch (IOException e)
{
e.printStackTrace();
}
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
I want to play music in my app when application starts. I tried many codes but nothing is working for me and i'm not getting any error.Can somebody please help me regarding this issue.Thanks in advance.
public class Login extends Activity {
EditText edName, edPassword;
String userName,password;
MediaPlayer mp;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mp = MediaPlayer.create(getApplicationContext(), R.raw.startsound);
ActionBar actionBar = getActionBar();
actionBar.hide();
edName = (EditText) findViewById(R.id.editText1);
edPassword = (EditText) findViewById(R.id.editText2);
mp.start();
}
public void SignInClick(View V) {
userName = edName.getText().toString();
password = edPassword.getText().toString();
if (userName.equals("")) {
Toast.makeText(Login.this, "Username is empty", Toast.LENGTH_LONG).show();}
else if (password.equals("")) {
Toast.makeText(Login.this, "Password is empty", Toast.LENGTH_LONG).show();
}
else {
Intent intent=new Intent(Login.this,Home.class);
startActivity(intent);
}
}
Hope this helps, and should be a working example although I have not had chance to test it.
public static Music theme;
theme = createMusic("menutheme.mp3");
theme.setLooping(true);
theme.setVolume(0.85f);
theme.play();
public Music createMusic(String filename) {
try {
AssetFileDescriptor assetDescriptor = assets.openFd(filename);
return new AndroidMusic(assetDescriptor);
} catch (IOException e) {
throw new RuntimeException("Couldn't load music '" + filename + "'");
}
}
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import com.matt.framework.Music;
import java.io.IOException;
public class AndroidMusic implements Music, OnCompletionListener, OnSeekCompleteListener, OnPreparedListener, OnVideoSizeChangedListener {
MediaPlayer mediaPlayer;
boolean isPrepared = false;
public AndroidMusic(AssetFileDescriptor assetDescriptor) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
assetDescriptor.getStartOffset(),
assetDescriptor.getLength());
mediaPlayer.prepare();
isPrepared = true;
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnVideoSizeChangedListener(this);
} catch (Exception e) {
throw new RuntimeException("Couldn't load music");
}
}
#Override
public void dispose() {
if (this.mediaPlayer.isPlaying()){
this.mediaPlayer.stop();
}
this.mediaPlayer.release();
}
#Override
public boolean isLooping() {
return mediaPlayer.isLooping();
}
#Override
public boolean isPlaying() {
return this.mediaPlayer.isPlaying();
}
#Override
public boolean isStopped() {
return !isPrepared;
}
#Override
public void pause() {
if (this.mediaPlayer.isPlaying())
mediaPlayer.pause();
}
#Override
public void play() {
if (this.mediaPlayer.isPlaying())
return;
try {
synchronized (this) {
if (!isPrepared)
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void setLooping(boolean isLooping) {
mediaPlayer.setLooping(isLooping);
}
#Override
public void setVolume(float volume) {
mediaPlayer.setVolume(volume, volume);
}
#Override
public void stop() {
if (this.mediaPlayer.isPlaying() == true){
this.mediaPlayer.stop();
synchronized (this) {
isPrepared = false;
}}
}
#Override
public void onCompletion(MediaPlayer player) {
synchronized (this) {
isPrepared = false;
}
}
#Override
public void seekBegin() {
mediaPlayer.seekTo(0);
}
#Override
public void onPrepared(MediaPlayer player) {
// TODO Auto-generated method stub
synchronized (this) {
isPrepared = true;
}
}
#Override
public void onSeekComplete(MediaPlayer player) {
// TODO Auto-generated method stub
}
#Override
public void onVideoSizeChanged(MediaPlayer player, int width, int height) {
// TODO Auto-generated method stub
}
}
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();
}
}
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();