Can't seek mp3 more than 50% with MediaPlayer in AsyncTask - android

seeking is not work correctly in my code,
I can only seek exactly in first half of my files,
I tested with mp3 in {30min, 60min, 90min, 120min} and don't work, but with mp4 it's ok.
public class Player extends AsyncTask<Integer, Integer, Integer> implements
OnBufferingUpdateListener, OnCompletionListener, OnErrorListener {
private static MediaPlayer mp;
protected static Player PLAYER = null;
public Player(){
mp = Defined.mp;
mp.setOnBufferingUpdateListener(this);
mp.setOnCompletionListener(this);
mp.setOnErrorListener(this);
}
doInBackground:
#Override
protected Integer doInBackground(Integer... params) {
prepareFileToPlay();
mp.start();
startProgress();
return null;
}
prepare File:
protected void prepareFileToPlay(){
String url="http://192.168.1.2/test10.mp3"; //mp3 duration: 60min
mp.reset();
try {
mp.setDataSource(url);
mp.prepare();
publishProgress(PLAYING);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Play function:
public static void play(){
if(PLAYER != null) PLAYER.cancel(true);
PLAYER = new Player();
PLAYER.execute("");
}
seek function:
public static void seekTo(int time){
//mp.seekTo(time);
//mp.seekTo(mp.getDuration()-10000); //seekTo 59:50
//mp.seekTo(mp.getDuration()-60000); //seekTo 59:00
Log.v("player", "CurrentPosition: "+ mp.getCurrentPosition() + " Duration:"+ mp.getDuration()); //Duration: 60 min
}

I was checking my application in BlueStacks, but I understand that this issue is dedicated to BlueStacks and this is not a public issue and it's not important...

Related

MediaController with MediaPlayer in Service getDuration error

In my app I have an audio player Activity which simply shows the current song title and album cover art together with a MediaController. I also have a Service which implements MediaController.MediaPlayerControl and which uses a MediaPlayer for playback.
In general everything works fine - the Activity binds to the Service and sets the MediaController to control the MediaPlayer.
The problem comes when starting a new song but ONLY when the MediaController is shown on the screen. If it is hidden or even if I leave the Activity using BACK and return to the home screen, the 'playlist' is processed without a problem. If the MediaContoller is visible, however, the player dies silently and the seek / progress bar shows a start and end time of 466:36:07 and logcat shows...
attempt to call getDuration without a valid mediaplayer
I don't get an unhandled exception stacktrace in logcat - just that message and MediaPlayer simply stops playing. I've Googled for the error and get nearly 3000 hits (most of which are for questions here on SO) but I can't find a situation which matches mine.
Relevant Activity code...
public class AudioPlayerActivity extends Activity
implements OnKeyListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
// Find views here
controller = new MyMediaController(this);
controller.setAnchorView(ll);
controller.setOnKeyListener(this);
}
#Override
protected void onResume() {
super.onResume();
mBound = bindService(new Intent(this, MusicPlayerService.class), mConnection, Context.BIND_AUTO_CREATE);
try {
getCurrentItem();
mediaFilename = currentItem.getTrackName();
coverArtPath = currentItem.getMediaArtUrl();
updateTrackDetails();
Intent playerServiceIntent = new Intent(this, MusicPlayerService.class);
startService(playerServiceIntent);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void showMediaController() {
// Called by onTouchEvent(...)` when the screen is touched
if (mBound) {
controller.setMediaPlayer(mService);
controller.setEnabled(true);
controller.show(0);
}
}
}
The Service has the following code...
public class NDroidTEMusicPlayerService extends Service
implements MediaPlayer.OnPreparedListener,
MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener,
AudioManager.OnAudioFocusChangeListener,
MediaPlayerControl {
private void setupMediaPlayer() {
...
try {
mMediaPlayer.setDataSource(trackUrl);
mMediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer mp) {
stop();
mp.reset();
currentItem = playList.getNextItem(isRepeating);
Intent i = new Intent(MYAPP.ACTION_MYAPP_UPDATE_PLAY_VIEW);
i.putExtra("current_item", currentItem);
sendBroadcast(i);
setupMediaPlayer();
}
#Override
public int getDuration() {
int duration = 0;
if (mMediaPlayer != null)
duration = mMediaPlayer.getDuration();
return duration;
}
}

How to Play the online streaming radio in Android

I am developing one application where i want to play live stream radio. I have an url using which i will stream the radio and play. I have a play button by clicking which i want to play the radio. For that, i have written some code which is not at all working. Here is my code:
mp = new MediaPlayer();
try {
mp.setOnPreparedListener(this);
Log.d("Testing", "start111");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
String url="xxxxxx";
mp.setDataSource(url);
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.d("Testing", "Exception ::: 1111 "+e.getMessage());
} catch (IllegalStateException e) {
Log.d("Testing", "Exception ::: 2222 "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d("Testing", "IOException ::: 3333 "+e.getMessage());
e.printStackTrace();
}
Can anyone please help me??
You can find good information regarding radio streaming.
Github radio streaming example
and also there is a question in SOF which can also be helpful
Stackoverflow radio streaming example
Hope it will help. thanks
Try this.
public class RadioStream extends Activity {
private final static String stream = "http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p";
Button play;
MediaPlayer mediaPlayer;
boolean started = false;
boolean prepared = false;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_stream);
play = (Button) findViewById(R.id.play);
play.setEnabled(false);
play.setText("Loading..");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started) {
mediaPlayer.pause();
started = false;
play.setText("Play");
} else {
mediaPlayer.start();
started = true;
play.setText("Pause");
}
}
});
new PlayTask().execute(stream);
}
#Override
protected void onPause() {
super.onPause();
/* if(started)
mediaPlayer.pause();*/
}
#Override
protected void onResume() {
super.onResume();
/*if(started)
mediaPlayer.start();*/
}
#Override
protected void onDestroy() {
super.onDestroy();
// mediaPlayer.release();
}
private class PlayTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
play.setEnabled(true);
play.setText("Play");
}
}
}
Please do try the code below and call the given method at the on create of your activity or at the onclick listener of your button. Remember to handle the stop and start button the imgV is an imageView for my button.
private MediaPlayer player;
private void startMediaPlayer() {
String url = "http:yoururl.com"; // your URL here
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(isPlaying){
try {
mediaPlayer.prepareAsync();
progress.setVisibility(View.VISIBLE);
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
}
boolean isPlaying = true;
private void startPlaying() {
isPlaying = true;
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
imgV.setImageResource(R.drawable.stop);
}
private void stopPlaying() {
if (mediaPlayer.isPlaying()) {
isPlaying = false;
mediaPlayer.stop();
mediaPlayer.release();
initializeMediaPlayer();
}
imgV.setImageResource(R.drawable.play);
}

Working with MP3 sound in Processing for Android ( need to stop )

I am developing an app for Android devices using Processing 2.0, now I have playMP3(); function but need to stop the sound using stopMP3();. I tried everything but what is the best way to load an mp3 and play/stop using processing?, snd.stop(); within the stopMP3 function does not work...
import android.media.*;
import android.content.res.*;
...
MediaPlayer snd;
...
void setup()
{
MediaPlayer snd = new MediaPlayer();
}
...
void playMP3()
{
try {
AssetManager assets = this.getAssets();
AssetFileDescriptor fd = assets.openFd("loop1.mp3");
snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
snd.prepare();
snd.start();
snd.setLooping(true);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void stopMP3(){
????
}
this is a simple sample for media player
private MediaPlayer m_Player;
//Start Play Function
private void startPlaying() {
m_Player = new MediaPlayer();
m_Player.setOnCompletionListener(onComplete);
try {
if(m_Player.isPlaying())
stopPlaying();
m_Player.setDataSource(m_FileName);
m_Player.prepare();
m_Player.start();
} catch (IOException e) {
}
}
//Stop Play Function
private void stopPlaying() {
m_Player.stop();
m_Player.reset();
m_Player = null;
}
//and this is onComplete Listener
MediaPlayer.OnCompletionListener onComplete = new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
stopPlaying();
}
};
i hope it's helping you

Videoplayer doesn't play video in splah screen

I have a splahs screen in my application and i am playing a video on that activity. But in some Android versions ( i mean old ) the video doesnt play. i dont know what to do..
here is some of my code
public void PlayVideo(){
try{
videoPlayer.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.afad_splash_ip4));
videoPlayer.prepare();
}
catch (Exception e){
}
try {
AssetFileDescriptor descriptor = getAssets().openFd("splash.mp4");
videoPlayer.reset();
videoPlayer.setDataSource(descriptor.getFileDescriptor());
videoPlayer.prepare();
}
catch (Exception ex)
{
try
{
Log.v("video ", "catch");
videoPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
videoPlayer.setVolume(0f, 0f);
videoPlayer.start();
videoPlayer.setLooping(false);
videoPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Intent i = new Intent(VideoSplash.this,ListActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
overridePendingTransition(R.anim.slide_in_top,R.anim.slide_out_bottom);
finish();
}
});
}
catch (Exception e)
{ //TODO
//Burada Video yerine resim koymalısın
//Kimi cihazlarda video oynamayabilir
Log.v("resim", "catch");
//Thats where i want to put a pic as a backgroun to my SurfaceView. and make it wait 10 secs
// videoSurface.setBackgroundDrawable(getResources().getDrawable(R.drawable.son_frame));
}
//TODO
//Burada Video yerine resim koymalısın
//Kimi cihazlarda video oynamayabilir
}
}
Try this code will help you
public class VideoPlayerActivity extends Activity implements OnErrorListener,
OnPreparedListener {
LoadAsyncTask video_async_task;
private VideoView mVideoView
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.video);
mVideoView = (VideoView) findViewById(R.id.mysurfaceview);
mVideoView.setMediaController(myctrl);
mVideoView.requestFocus();
video_async_task = new LoadAsyncTask();
video_async_task.execute();
}
private class LoadAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
mVideoView.setVideoURI(Uri.parse(path));
}
}

Android: Stop sound files playing at once

In the application I am currently writing, a user is able to select an entry from the database and play the contents of that entry: an entry is made up of a number of sound files (without a limit). In my application, I return the URI locations of the sound files of an entry (which have been stored in my database) in a List. The code is as follows:
public void audioPlayer() {
// set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
DatabaseHandler db = new DatabaseHandler(this);
Entry retrieveEntry = new Entry();
retrieveEntry = db.getEntry();
List<String> path = retrieveEntry.getAudioUri();
path.size();
System.out.println("PATH SIZE: " +path.size());
System.out.println("FILEZ: " + path);
Iterator<String> i = path.iterator();
String myAudio;
int count = 0;
while (i.hasNext()) {
System.out.println(count);
myAudio = i.next();
System.out.println("MY AUDIO: " + myAudio);
MediaPlayer player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
player.stop();
player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
count++;
}
}
My users require that there be user input for playing a file - is there a way to play the first file, then wait for the user to press the button, then play the second file, then wait for the user to press the button, etc.? At the moment, when the play button is pressed, all of the sound files that have been returned get played at the same time, rather than one after the other.
Thanks in advance for any help provided!
You can use this class to play a playlist. This will start one audio, when that audio finishes, it will start playing next audio till the end of the list. If you want to play the playlist in looping i.e start first audio after reaching end, then pass isLooping=true in startPlayingPlaylist(list,looping)
AudioPlayer player = new AudioPlayer();
player.startPlayingPlaylist(list, false);
Class
public class AudioPlayer{
MediaPlayer player = null;
ArrayList<String> playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list, boolean looping){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.setLooping(looping);
player.start();
// Set onCompletion listener
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(player.isLooping()==false){
player.release();
player = null;
}
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
Edit:
The class below receives a list of audios, then plays first Audio. It plays next audio when user calls startNextAudio() You can use any one of these according to your requirements
public class AudioPlayer{
MediaPlayer player = null;
ArrayList playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.start();
// Set onCompletion listener
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void startNextAudio(){
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
Log.i("AudioPlayer","Playlist reached at the end");
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
One approach would be to implement the MediaPlayer.OnCompletionListener interface. This gives you the MediaPlayer.onCompletion() callback method which you could use like so:
#Override
public void onCompletion(MediaPlayer mp) {
if (i.hasNext) {
// ...hand mp the next file
// ...show the user the 'play next' button
}
}
Note you also will need to call the MediaPlayer.setOnCompletionListener() method in your setup.

Categories

Resources