I'm playing a video (from youtube) using a VideoView, like this:
VideoView video = (ViewView) this.findViewById(R.id.youtube_video);
MediaController controllers = new MediaController(this);
controllers.setAnchorView(video);
video.setMediaController(controllers);
video.setVideoURI(videoUri);
video.start()
I would like to be able to mute the video, but so far the only thing I found is:
AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
Which works fine in that the video is muted, but the problem is that all of the streamed music is muted, and if there's another video (or audio) which I want to play it's also muted.
Is there a way to just target the specific stream to be muted?
Thanks.
After digging into every possible source of information I managed to find, I came up with the following solution and thought it might benefit others in the future:
public class Player extends VideoView implements OnPreparedListener, OnCompletionListener, OnErrorListener {
private MediaPlayer mediaPlayer;
public Player(Context context, AttributeSet attributes) {
super(context, attributes);
this.setOnPreparedListener(this);
this.setOnCompletionListener(this);
this.setOnErrorListener(this);
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) { ... }
#Override
public void onCompletion(MediaPlayer mediaPlayer) { ... }
public void mute() {
this.setVolume(0);
}
public void unmute() {
this.setVolume(100);
}
private void setVolume(int amount) {
final int max = 100;
final double numerator = max - amount > 0 ? Math.log(max - amount) : 0;
final float volume = (float) (1 - (numerator / Math.log(max)));
this.mediaPlayer.setVolume(volume, volume);
}
}
It seems to working well for me, acting just like a VideoView with mute/unmute functionality.
It's possible to make the setVolume method public so that volume can be controlled outside of the scope of the class, but I just needed mute/unmute to be exposed.
put this code in oncreate() and also in onresume() for handle video view in better way...
VideoView videoview = (VideoView) findViewById(R.id.videoview);
videoview.setVideoPath(videopath);
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setVolume(0f, 0f);
mp.setLooping(true);
}
});
videoview.start();
If you are coding in kotlin, Just use this line of code
videoView.setOnPreparedListener { video->
video.setVolume(0f,0f)
}
I have a simpler method, by doing this you will have a mute/unmute button (this can be used for audio and videos);
//set global variable
//private Button mMuteButton;
//private static int aux = 0;
//private AudioManager mAudioManager;
//set the Mute button on clickListener
mMuteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if(aux % 2 == 0){
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
aux++;
} else {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
aux++;
}
}
});
}
Related
I am making a chat application and I have implemented the feature for sending audio messages.But here I find one thing which I don't want it to happen.It is that whenever my adapter gets updated,The media player starts loading again. In this way there will be an issue for if someone is listening to an audio and the user at other end sends a message ,the media player stops and it loads again.Here is the code of my adapter.
final MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
handler = new Handler();
try {
mediaPlayer.setOnCompletionListener(mediaPlayer1 -> {
mediaPlayer1.stop();
binding.audioSeekbar.setProgress(0);
});
if (mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer.setDataSource(finalUrlToLoad[1]);
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(mediaPlayer1 -> {
int totalDuration = mediaPlayer1.getDuration();
binding.totalDurationAudio.setText(createTimeLabel(totalDuration));
binding.loadingAudio.setVisibility(GONE);
binding.playPauseAudio.setVisibility(VISIBLE);
});
} catch (IOException e) {e.printStackTrace();}
binding.playPauseAudio.setOnClickListener(view -> {
if (mediaPlayer.isPlaying()){
handler.removeCallbacks(runnable);
mediaPlayer.pause();
binding.playPauseAudio.setImageResource(R.drawable.pause_to_play);
Drawable drawable = binding.playPauseAudio.getDrawable();
if( drawable instanceof AnimatedVectorDrawable) {
AnimatedVectorDrawable animation = (AnimatedVectorDrawable) drawable;
animation.start();
}
}else {
mediaPlayer.seekTo(binding.audioSeekbar.getProgress());
mediaPlayer.start();
handler.post(runnable);
binding.playPauseAudio.setImageResource(R.drawable.play_to_pause);
Drawable drawable = binding.playPauseAudio.getDrawable();
if( drawable instanceof AnimatedVectorDrawable) {
AnimatedVectorDrawable animation = (AnimatedVectorDrawable) drawable;
animation.start();
}
}
});
runnable = () -> {
int totalTime = mediaPlayer.getDuration();
binding.audioSeekbar.setMax(totalTime);
int currentPosition = mediaPlayer.getCurrentPosition();
binding.audioSeekbar.setProgress(currentPosition);
binding.totalDurationAudio.setText(createTimeLabel(totalTime));
Log.d("time", String.valueOf(currentPosition));
handler.postDelayed(runnable,1000);
};
binding.audioSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b){
mediaPlayer.seekTo(i);
seekBar.setProgress(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mediaPlayer.setOnBufferingUpdateListener((mediaPlayer1, i) -> binding.audioSeekbar.setSecondaryProgress(i));
Here finalurltoload[1] is the url for the audio.
Now what do I need to do in order to prevent loading it again and again.
I will be really grateful to who answer this question.
Thanks😊.
It's hard to tell from this code but I assume this is all set in your onBind event? If so, then this means every time RecyclerView creates a new holder and binds it, the associated media will be prepped and loaded, and whichever is the 'last holder to have been called with onBind, "wins" (and is what MediaPlayer will be loaded with). Since by default RecyclerView typically creates multiple holders up front, you are seeing your MediaPlayer being "loaded" multiple times.
You probably just don't want to do the initialization of each audio message in the onBind. Instead, just use the onBind event to initialize state variables (duration, progress, etc.) to some default value, hide them and bind the specific audio Uri. Then when the user takes some action like tapping on the holder, you unhide an indeterminate progress bar while the initialization takes place, and in the onPrepared() event unhide the state information (duration, progress, seekbar, etc.), and finally hide the indeterminate progress bar and start the audio.
I assume you are also sending over the sound file as part of your messaging app (i.e. not storing it on the web somewhere in a central location?), and this file gets stored in an app-specific storage location? If so, you don't need to worry about persisting the permission to that URI, but if that isn't the case you will.
First extract the media player code into singleton class like AudioManager.
Add few method like setMediaUpdateListener that set a callback for seek duration. and togglePlayPause to play or pause the audio.
Passed the message id or any unique identifier to the audio manager while playing the video.
In Adapter class onBind Method.
First Compare the id and playing Id is same like AudioManager.getInstance().isPlaying(messageId);
If yes then set the seekUpdatelistner to the audio manager class.
also update the play/pause icon based on AudioManager.isPlaying() method.
3.if user play other message by clicking play button. call AudioManager.play(message) method.In which we release the previous message and play the new one.
If current message is not playing then reset the view on non-playing state.
If Auto play is enabled then you need to check if audioManager is free then only you can play the last message otherwise ignored.
Like a class who are managing the audio for you and store all the state.
class AudioManager {
public static AudioManager instance;
final MediaPlayer mediaPlayer;
private AudioListener audioListener;
private Uri currentPlaying;
public AudioManager getInstance() {
if (instance == null) {
instance = new AudioManager();
}
}
public void play(Uri dataUri) {
if (mediaPlayer != null && currentPlaying == null || currentPlaying.equals(dataUri)) {
if (!mediaPlayer.isPlaying) {
mediaPlayer.play();
}
return;
} else if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
handler = new Handler();
try {
mediaPlayer.setOnCompletionListener(mediaPlayer1 -> {
mediaPlayer1.stop();
sendProgress(0);
});
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer.setDataSource(dataUri;
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(mediaPlayer1 -> {
int totalDuration = mediaPlayer1.getDuration();
sendTotalDuration(totalDuration);
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void pause() {
// update the pause code.
}
public void sendProgress(int progress) {
if (audioListener != null) {
audioListener.onProgress(progress);
}
}
public void sendTotalDuration(int duration) {
if (audioListener != null) {
audioListener.onTotalDuraration(duration);
}
}
public void AudioListener(AudioListener audioListener) {
this.audioListener = audioListener;
}
public interface AudioListener {
void onProgress(int progress);
void onTotalDuraration(int duration);
void onAudioPlayed();
void onAudioPaused():
}
}
Hello StackOverflow's users,
I'm developing a Music Player App for android. In my main activity when the user clicks on a song I start a new intent that displays PlayerActivity. In there, I initialize a MediaPlayer and all the other UI elements. When the user clicks the back button, I bring them back to the main activity and the song continues to play in the background. The same thing happens if they exit the application. Now I was wondering if it's fine to do something like this or if I should instead start a new Service for the MediaPlayer from the PlayerActivity class instead of doing it in there.
PlayerActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Bundle extras = getIntent().getExtras();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
getWindow().setNavigationBarDividerColor(getResources().getColor(R.color.white));
}
playBtn = findViewById(R.id.btn_play);
artImage = findViewById(R.id.art);
remainingTimeLabel = findViewById(R.id.current_song_duration);
totalTimeLabel = findViewById(R.id.total_duration);
manager = MainActivity.getManager();
Song song = manager.getCurrentSong();
boolean wasCall = extras != null && extras.containsKey("call");
if (!wasCall && manager.hasStarted()) {
MediaPlayer mediaPlayer = manager.getMediaPlayer();
mediaPlayer.pause();
mediaPlayer.stop();
}
if (!wasCall) {
mp = MediaPlayer.create(this, Uri.parse(song.getPath()));
mp.setLooping(true);
mp.seekTo(0);
mp.setVolume(0.5f, 0.5f);
} else {
mp = manager.getMediaPlayer();
mp.setLooping(true);
mp.setVolume(0.5f, 0.5f);
}
totalTime = mp.getDuration();
artImage.setImageBitmap(Bitmap.createScaledBitmap(song.getIcon(), 250, 250, true));
totalTimeLabel.setText(createTimeLabel(totalTime));
songName = findViewById(R.id.songName);
songName.setText(song.getName());
songAuthor = findViewById(R.id.songAuthor);
songAuthor.setText(song.getArtist());
Toolbar toolbar = findViewById(R.id.player_top_bar);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
assert toolbar.getNavigationIcon() != null;
toolbar.getNavigationIcon().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>MySound</font>"));
positionBar = findViewById(R.id.seek_song_progressbar);
positionBar.setMax(totalTime);
positionBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
positionBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
LinearLayout layout = findViewById(R.id.player_control);
layout.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
new Thread(() -> {
while (mp != null) {
try {
Message msg = new Message();
msg.what = mp.getCurrentPosition();
handler.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
this.action = SongEndAction.REPEAT;
mp.start();
manager.setMediaPlayer(mp);
}
Here is a Music Service that I implemented in my book.
https://github.com/Wickapps/Practical-Android-MusicService
This implementation includes play, stop, and seek forward, but you could add other functions.
Service is the best architecture for future scalability.
There is a MainActivity.java which starts the service.
MusicService.java is the service implementation.
Hope this helps.
If you want your app to keep playing audio while it's in background ( like spotify ), then yes, it is a must to use a foreground service.
Unfortunately it's more complex than your current implementation.
This is a nice starting point : https://developer.android.com/guide/topics/media-apps/audio-app/building-an-audio-app
I have made an imageView animate from one side to the other side of the screen. Here is the java code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageView = findViewById(R.id.imageView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
handleAnimation(imageView);
}
});
}
public void handleAnimation(View view) {
ObjectAnimator animatorX = ObjectAnimator.ofFloat(view, "x", 1000f);
animatorX.setDuration(2000);
animatorX.start();
}
}
And this is what we see when user clicks on the ANIMATE button:
Now my question is that how I can make a video file by capturing the animated imageView ?
EDIT:
What I need is: I want to make an app which takes some photos from the user and make some animations on the photos and some effects and also mix them with a desired sound and at the end exports a video clip. And of course if I can I would rather make all these things hidden.
You have to record your screen and then crop the video using your view's xy coordinates. You can record your screen using the MediaProject API on android (5) and above.
private VirtualDisplay mVirtualDisplay;
private MediaRecorder mMediaRecorder;
private MediaProjection mMediaProjection;
private MediaProjectionCallback callback;
MediaProjectionManager projectionManager = (MediaProjectionManager)
context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
mMediaProjection.registerCallback(callback, null);
initRecorder();
mMediaRecorder.prepare();
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
public void initRecorder() {
path = "/sdcard/Record/video" + ".mp4";
recId = "capture-" + System.currentTimeMillis() + ".mp4";
File myDirectory = new File(Environment.getExternalStorageDirectory(), "Record");
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(MainFragment.bitRate);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(MainFragment.DISPLAY_WIDTH,
MainFragment.DISPLAY_HEIGHT);
mMediaRecorder.setOutputFile(path);
}
private VirtualDisplay createVirtualDisplay() {
return mMediaProjection.createVirtualDisplay("MainActivity",
MainFragment.DISPLAY_WIDTH, MainFragment.DISPLAY_HEIGHT, MainFragment.screenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
}
public class MediaProjectionCallback extends MediaProjection.Callback {
#Override
public void onStop() {
mMediaRecorder.stop();
// mMediaRecorder.reset();
mMediaRecorder.release();
mMediaProjection.unregisterCallback(callback);
mMediaProjection = null;
mMediaRecorder = null;
}
Once done simply call mMediaProjection.stop() to finish the recording and save the video as tmp
After which you can crop the video at the xy coordinates that your view is position using FFmpeg
ffmpeg -i in.mp4 -filter:v "crop=out_w:out_h:x:y" out.mp4
Where the options are as follows:
out_w is the width of the output rectangle
out_h is the height of the output rectangle
x and y specify the top left corner of the output rectangle
so in your case
String cmd ="-i '"+ tmpVideoPath+"' -filter:v "+"'crop="+view.getWidth()+":"+view.getHeight()+":"+view.getX()+":"+view.getY()+"'"+" -c:a copy "+outVideoPath
FFmpeg ffmpeg = FFmpeg.getInstance(context);
// to execute "ffmpeg -version" command you just need to pass "-version"
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onProgress(String message) {}
#Override
public void onFailure(String message) {}
#Override
public void onSuccess(String message) {}
#Override
public void onFinish() {}
});
There are two possible approaches to archive this.
1- You can acchive this by using the javacv library (FFmpeg) to combine a set of bitmaps taken from the view
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("/sdcard/test.mp4",256,256);
try {
recorder.setVideoCodec(avcodec.AV_CODEC_ID_MPEG4);
recorder.setFormat("mp4");
recorder.setFrameRate(30);
recorder.setPixelFormat(avutil.PIX_FMT_YUV420P10);
recorder.setVideoBitrate(1200);
recorder.startUnsafe();
for (int i=0;i< 5;i++)
{
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
view.setDrawingCacheEnabled(false);
recorder.record(bitmap);
}
recorder.stop();
}
catch (Exception e){
e.printStackTrace();
}
all the code of using this library is here
2- You can use this link for record the screen and use as per your need.
Screen Recorder
I have problems about how to implement PlaybackParams to set video speed:
public PlaybackParams getPlaybackParams ()
Added in API level 23
Gets the playback rate using PlaybackParams.
PlaybackParams setSpeed (float speed) //Sets the speed factor.
Returns:
the playback rate being used.
Throws IllegalStateException:
if the internal sync engine or the audio track has not been initialized.
This is my code:
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mp.setPlaybackParams(new PlaybackParams().setSpeed(1.f));
if (mPlaybackState == PlaybackState.PLAYING) { mVideoView.start();}
}
});
You are getting an IllegalStateException while calling the 'setPlayParams' method, because you're not doing PlaybackParams params = mp.getPlaybackParams(), set the speed and then pass it to mp.setPlaybackParams()! Set the speed DIRECTLY while calling the mp.getPlayParams()!
MediaPlayer mp = ...;
float speed = 0.55f;
mp.setPlaybackParams(mp.getPlaybackParams().setSpeed(speed));
After many try i find a solution.
Example how use VideoView
final VideoView mVideoView = findViewById(R.id.videoView);
mVideoView.setVideoPath(Environment.getExternalStorageDirectory() + "/bluetooth/test.webm"); //Path of your file video
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mp.setPlaybackParams(mp.getPlaybackParams().setSpeed(0.55f));
mVideoView.start();
}
});
MediaController media = new MediaController(this); //this is for play and restart play manually
media.setAnchorView(mVideoView);
mVideoView.setMediaController(media);
//mVideoView.start();
You have not started the Media Playe..
Try This Code:
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start()
mp.setPlaybackParams(new PlaybackParams().setSpeed(1.f));
}
Could someone show me or teach me how I can download 5 or more mp3 in a file and playing them in my app. I've searched about it but all of people how has asked this, nothing explained it well. I don't want to download only one mp3, but multiple mp3s in a file.here is main.java
public class StreamingMp3Player extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
public EditText editTextSongURL;
private MediaPlayer mediaPlayer;
private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
private final Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
/** This method initialise all the views in project*/
private void initView() {
buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
editTextSongURL.setText(R.string.testsong_20_sec);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.ButtonTestPlayPause){
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource(editTextSongURL.getText().toString()); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.button_pause);
}else {
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.button_play);
}
primarySeekBarProgressUpdater();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.SeekBarTestPlay){
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if(mediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
buttonPlayPause.setImageResource(R.drawable.button_play);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
seekBarProgress.setSecondaryProgress(percent);
}
You'll need to use 3rd party libraries to support MP3 playback, as it is not included in the standard library. See Wikipedia for a list of alternatives.
For the downloading part, use an URLConnection to get an InputStream on the file and write it to a FileOutputStream. This might help, too: Working unbuffered Streams