I am using media player to stream a video. It only plays the audio but not the video. Could anyone help? My code is below.
public class VideoViewApplication extends Application {
#Override
public void onCreate() {
}
#Override
public void onTerminate() {
}
}
public class VideoViewDemo extends Activity implements
OnErrorListener,OnBufferingUpdateListener, OnCompletionListener,
MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
private static final String TAG = "VideoViewDemo";
private MediaPlayer mp;
private EditText mPath;
private SurfaceHolder holder;
private ImageButton mPlay;
private ImageButton mPause;
private ImageButton mReset;
private ImageButton mStop;
private String current;
private SurfaceView mPreview;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPreview = (SurfaceView) findViewById(R.id.surface);
mPath = (EditText) findViewById(R.id.path);
mPath.setText("rtsp://video2.americafree.tv/AFTVHorrorH26496.sdp");
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mReset = (ImageButton) findViewById(R.id.reset);
mStop = (ImageButton) findViewById(R.id.stop);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
playVideo();
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mp != null) {
mp.pause();
}
}
});
mReset.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mp != null) {
mp.seekTo(0);
}
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mp != null) {
current = null;
mp.stop();
mp.release();
}
}
});
// getWindow().setFormat(PixelFormat.TRANSPARENT);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setFixedSize(100, 100);
runOnUiThread(new Runnable(){
public void run(){
playVideo();
}
});
}
private void playVideo() {
try {
final String path = mPath.getText().toString();
Log.v(TAG, "path: " + path);
if (path.equals(current) && mp != null) {
mp.start();
return;
}
current = path;
mp = new MediaPlayer();
mp.setOnErrorListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setScreenOnWhilePlaying(true);
mp.setDisplay(mPreview.getHolder());
mp.setDataSource(path);
mp.prepare();
Log.v(TAG, "Duration: ===>" + mp.getDuration());
mp.start();
} catch (Exception e) {
Log.e(TAG, "error: "+ e.getMessage(), e);
if (mp != null) {
mp.stop();
mp.release();
}
}
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceCreated(SurfaceHolder arg0) {
Log.d(TAG, "surfaceCreated called");
}
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.d(TAG, "surfaceDestroyed called");
}
public void onPrepared(MediaPlayer arg0) {
Log.d(TAG, "onPrepared called");
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
Log.d(TAG, "onBufferingUpdate called ---> percent:" + percent);
}
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
Log.e(TAG, "onError---> what:"+what+" extra:"+extra);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="#+id/path"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<SurfaceView
android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</SurfaceView>
<LinearLayout
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
>
<ImageButton android:id="#+id/play"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/play"/>
<ImageButton android:id="#+id/pause"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/pause"/>
<ImageButton android:id="#+id/reset"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/reset"/>
<ImageButton android:id="#+id/stop"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/stop"/>
</LinearLayout>
</LinearLayout>
I had this problem and solved it by setting the type using this depreciated method.
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Worth a try, and if it works you could investigate why the type isn't automatically set as it is supposed to be.
I had the same problem and it was due to the surface not being ready to play back video.
You should try and call playVideo() from the surfaceCreated() handler.
public void surfaceCreated(SurfaceHolder holder) {
runOnUiThread(new Runnable(){
public void run(){
playVideo();
}
});
}
I had this problem and solved it by adding in my release function visible=gone to surfaceview:
public void release() {
if (mMediaPlayer != null) {
setVisibility(View.GONE);
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;}
}
and set visible=visible in onprepared function:
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
audio=false; video=false; int ty=mp.getTrackInfo().length;
for (int i=0; i<ty;i++)
{
if (mp.getAudioTrack()>-1) {audio=true;}
if (mp.getVideoTrack()>-1) {video=true;}
}
if (((audio==false)&&(skip==true))||((video==false)&&(skip2==true))||((video==true)&&(skip4==true)))
{ notifybar("...");
nexttr();} else {
if (vis==true) {
if (video==false) {
if (mVisualizerView.getVisibility()!=View.VISIBLE) {mVisualizerView.setVisibility(View.VISIBLE);}
mVisualizerView.link(videoView.getAudioSessionId());
vis2=true;
} else if (vis2==true){
mVisualizerView.release();
mVisualizerView.setVisibility(View.GONE);
vis2=false;
}}
//this
if (video==true) {
if (videoView.getVisibility()!=View.VISIBLE) {videoView.setVisibility(View.VISIBLE);}
} else {if (videoView.getVisibility()!=View.INVISIBLE) {videoView.setVisibility(View.INVISIBLE);}
}
Related
I am making a music player application in android. The application has
MainActivity.java (with corresponding XML File:activity_main): This Activity has a listview that displays the list of all songs available.
PlayerScreen.java (with corresponding XML File:activity_player_screen): When a song is clicked on the first activity, this activity is launched and it plays that particular song. This activity has 3 Buttons (Play/Pause, NextSong, PreviousSong) and a seekbar.
Now this is where I am facing the problem
I have created a separate class (SeekBarThread.java) for implementing seekbar of the activity_player_screen using Threading.
The Problem is that when I call the start method for my thread class from PlayerScreen.java, nothing happens. No exception is thrown. The song keeps on playing but the widgets of the activity_player_screen stop working i.e. I can't pause the song aur play the next song. The seekbar also doesn't work.
I think I am not able to link the activity_player_screen file with both PlayerScreen.java and SeekBarThread.java properly.
This is the call to the Thread class from PlayerScreen.java
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
I don't really have an idea to get rid of the anomaly so I passed the seekbar object and mediaplayer object reference and the current context reference to the SeekBarThread class. But it didn't work.
Here is the SeekBarThread.java class code:
public class SeekBarThread implements Runnable{
private PlayerScreen myPlayerScreen;
private SeekBar seekBar;
private MediaPlayer mp;
private Context context;
public SeekBarThread(Context context, SeekBar seekBar, MediaPlayer mp) {
this.context = context;
this.seekBar = seekBar;
this.mp = mp;
}
public void run() {
((Activity)context).setContentView(R.layout.activity_player_screen);
seekBar.setMax(mp.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
int totalduration = mp.getDuration();
int currentposition = 0;
while(currentposition < totalduration) {
try {
sleep(500);
currentposition = mp.getCurrentPosition();
seekBar.setProgress(currentposition);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
activity_player_screen XML File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_player_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="prakhar.simplemusicplayer20.PlayerScreen">
<Button
android:id="#+id/play_pause"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:background="#drawable/pause" />
<Button
android:id="#+id/next_song"
android:layout_height="42dp"
android:layout_width="42dp"
android:background="#drawable/next"
android:layout_marginEnd="25dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/prev_song"
android:layout_height="42dp"
android:layout_width="42dp"
android:background="#drawable/previous"
android:layout_marginStart="25dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<Button
android:text="F"
android:layout_width="42dp"
android:layout_height="42dp"
android:id="#+id/forward_song"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/next_song"
android:layout_marginEnd="22dp" />
<Button
android:text="R"
android:layout_width="42dp"
android:layout_height="42dp"
android:id="#+id/rewind_song"
android:layout_marginEnd="23dp"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/play_pause" />
<SeekBar
android:id="#+id/seek_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="26dp"
android:layout_above="#+id/play_pause"
android:layout_alignParentStart="true" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="146dp"
android:id="#+id/details_text_view" />
</RelativeLayout>
Here is the PlayerScreen.java class:
public class PlayerScreen extends AppCompatActivity implements View.OnClickListener{
private Button playPause, nextSong, prevSong;
public SeekBar mySeekBar;
private int count = 0;
public MediaPlayer mediaPlayer;
private Bundle newBundle = new Bundle();
private Intent newIntent;
private int pos;
private ArrayList<String> name;
private ArrayList<String> path;
private SeekBarThread mySeekBarThread;
private Thread myThread;
private TextView detailsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_screen);
playPause = (Button)findViewById(R.id.play_pause);
nextSong = (Button)findViewById(R.id.next_song);
prevSong = (Button)findViewById(R.id.prev_song);
mySeekBar = (SeekBar)findViewById(R.id.seek_bar);
detailsTextView = (TextView)findViewById(R.id.details_text_view);
playPause.setOnClickListener(this);
nextSong.setOnClickListener(this);
prevSong.setOnClickListener(this);
newIntent = this.getIntent();
newBundle = newIntent.getExtras();
name = newBundle.getStringArrayList("title");
path = newBundle.getStringArrayList("songpath");
pos = newBundle.getInt("post");
detailsTextView.setText(name.get(pos));
mediaPlayer = new MediaPlayer();
setMediaPlayer(pos);
}
public void setMediaPlayer(int position) {
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
File mySong = new File(path.get(pos));
mediaPlayer = new MediaPlayer();
FileInputStream is = null;
try {
is = new FileInputStream(mySong);
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setDataSource(is.getFD());
}
catch(IOException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.prepare();
}
catch(IOException ex) {
ex.printStackTrace();
}
finally {
if(is != null) {
try {
is.close();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}
mediaPlayer.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.play_pause:
count++;
if(count%2 == 0) {
v.setBackgroundResource(R.drawable.pause);
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
}
else {
v.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
break;
case R.id.next_song:
mediaPlayer.stop();
pos = pos + 1;
setMediaPlayer(pos);
break;
case R.id.prev_song:
mediaPlayer.stop();
pos = pos - 1;
setMediaPlayer(pos);
break;
}
}
}
Most of the onCreate() code for this is class is dealing with which song to play based on the user's choice from the previous activity. And since the song is being played, i don't think there is a problem in that part of the code.
#prakhar, Going through the code, I have found the following issues:
1) In SeekBarThread class in run() method setContentView() should not set,as it is already set in the activity class, as your are not reinitializing the click listeners.
2) Also the seekbarchangeListener should not be set in run() method and should be set in the main activity itself, as it doesn't need reinitalizing all the time.
3) The important point here is that your are initializing the SeekBarThread class before the initialization of MediaPlayer and hence there is no action even after seeking the seekbar.
A detailed code with the above modifications rectified.
public class PlayerScreen extends AppCompatActivity implements View.OnClickListener {
private Button playPause, nextSong, prevSong;
public SeekBar mySeekBar;
private int count = 0;
public MediaPlayer mediaPlayer;
private Bundle newBundle = new Bundle();
private Intent newIntent;
private int pos;
private ArrayList<String> name;
private ArrayList<String> path;
private SeekBarThread mySeekBarThread;
private Thread myThread;
private TextView detailsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playPause = (Button) findViewById(R.id.play_pause);
nextSong = (Button) findViewById(R.id.next_song);
prevSong = (Button) findViewById(R.id.prev_song);
mySeekBar = (SeekBar) findViewById(R.id.seek_bar);
detailsTextView = (TextView) findViewById(R.id.details_text_view);
playPause.setOnClickListener(this);
nextSong.setOnClickListener(this);
prevSong.setOnClickListener(this);
mySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
newIntent = this.getIntent();
newBundle = newIntent.getExtras();
name = newBundle.getStringArrayList("title");
pos = newBundle.getInt("post");
detailsTextView.setText(name.get(pos));
mediaPlayer = new MediaPlayer();
setMediaPlayer(pos);
}
public void setMediaPlayer(int position) {
File mySong = new File(path.get(pos));
mediaPlayer = new MediaPlayer();
FileInputStream is = null;
try {
is = new FileInputStream(mySong);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setDataSource(is.getFD());
} catch (IOException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepare();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
mediaPlayer.start();
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play_pause:
count++;
if (count % 2 == 0) {
v.setBackgroundResource(R.drawable.pause);
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
} else {
v.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
break;
case R.id.next_song:
mediaPlayer.stop();
pos = pos + 1;
setMediaPlayer(pos);
break;
case R.id.prev_song:
mediaPlayer.stop();
pos = pos - 1;
setMediaPlayer(pos);
break;
}
}
}
public class SeekBarThread implements Runnable{
private SeekBar seekBar;
private MediaPlayer mp;
private Context context;
public SeekBarThread(Context context, SeekBar seekBar, MediaPlayer mp) {
this.context = context;
this.seekBar = seekBar;
this.mp = mp;
}
public void run() {
seekBar.setMax(mp.getDuration());
int totalduration = mp.getDuration();
int currentposition = 0;
while(currentposition < totalduration) {
try {
sleep(500);
currentposition = mp.getCurrentPosition();
seekBar.setProgress(currentposition);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
I used these codes from this reference. They want to click on button to play music and then click again to stop playing. (in their comment they said it was worked for them but hanging for me)
It is work just for first time. I mean for first click the music is playing. for second click the music is stop but for third click the phone emulator show this error:
unfortunately your program has stopped.
This is my code:
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btnRain);
//mp = MediaPlayer.create(this, R.raw.rain);
mp = MediaPlayer.create(MainActivity.this, R.raw.rain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
//MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
// mp.start();
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
mp.release();
}
else {
mp.start();
}
}
});
}
In onCreate initialize mp as :
mp = new MediaPlayer();
The error is you are releasing the media player object mp, which destroys the object, call reset method instead of release.
if (mp.isPlaying())
{
mp.stop();
mp.reset();
}
else {
mp = MediaPlayer.create(LegalActivity.this, R.raw.free1);
mp.start();
}
use this below code for play and pause the music:
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btnRain);
//mp = MediaPlayer.create(this, R.raw.rain);
mp = MediaPlayer.create(MainActivity.this, R.raw.rain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
//MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
// mp.start();
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
}
else {
mp.start();
}
}
});
}
This is an AUDIO activity that works fine and it allows you to upload songs with a spinner.
public class AUDIO extends Activity{
Spinner spCanciones;
Button btnRep,btnGra,btnParar;
File audios;
String cancionSelec;
String arquivoGravar;
private MediaPlayer mediaplayer;
private boolean pause;
private MediaRecorder mediaRecorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
spCanciones=(Spinner)findViewById(R.id.spCanciones);
btnGra=(Button)findViewById(R.id.btnGra);
btnParar=(Button)findViewById(R.id.btnParar);
btnRep=(Button)findViewById(R.id.btnRep);
mediaplayer=new MediaPlayer();
enlazarSpinner();
//REPRODUCIR
btnRep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reproducir();
}
});
//PARAR
btnParar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaplayer.isPlaying())
mediaplayer.stop();
pause=false;
}
});
//GRABAR
btnGra.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
grabarAudio();
}
});
}
public void enlazarSpinner(){
final ArrayList<String>songs=new ArrayList<>();
audios=new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/AUDIO/");
String [] play=audios.list();
for (int i=0;i<play.length;i++)songs.add(play[i]);
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, songs);
// Opcional: layout usuado para representar os datos no Spinner
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Enlace do adaptador co Spinner do Layout.
spCanciones.setAdapter(adaptador);
// Escoitador
spCanciones.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
cancionSelec = songs.get(pos);
Log.i("Cancion", cancionSelec);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); // Fin da clase anónima
}
public void reproducir(){
try {
mediaplayer.reset();
mediaplayer.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath()+"/AUDIO/"+cancionSelec);
mediaplayer.prepare();
mediaplayer.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("MULTIMEDIA",e.getMessage());
}
}
public void grabarAudio(){
String timeStamp = DateFormat.getDateTimeInstance().format(
new Date()).replaceAll(":", "").replaceAll("/", "_")
.replaceAll(" ", "_");
mediaRecorder = new MediaRecorder();
arquivoGravar = Environment.getExternalStorageDirectory().getAbsolutePath()+"/AUDIO/"+ timeStamp + ".3gp";
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setMaxDuration(10000);
mediaRecorder.setAudioEncodingBitRate(32768);
mediaRecorder.setAudioSamplingRate(8000); // No emulador só 8000 coma
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setOutputFile(arquivoGravar);
try {
mediaRecorder.prepare();
} catch (Exception e) {
// TODO Auto-generated catch block
mediaRecorder.reset();
}
mediaRecorder.start();
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setMessage("GRAVANDO").setPositiveButton(
"PREME PARA PARAR",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
});
dialog.show();
enlazarSpinner();
}
#Override
protected void onPause() {
super.onPause();
if (mediaplayer.isPlaying()){
mediaplayer.pause();
pause = true;
}
}
#Override
protected void onResume() {
super.onResume();
if (pause) {
mediaplayer.start();
pause = false;
}
}
#Override
protected void onSaveInstanceState(Bundle estado) {
estado.putBoolean("MEDIAPLAYER_PAUSE", pause);
super.onSaveInstanceState(estado);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.putBoolean("MEDIAPLAYER_PAUSE", false);
pause = savedInstanceState.getBoolean("MEDIAPLAYER_PAUSE");
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaplayer.isPlaying()) mediaplayer.stop();
if (mediaplayer != null) mediaplayer.release();
mediaplayer = null;
}
}
I am trying to play a song by using seek bar listener. But when I try to drag the progress bar then it is playing from beginning of the song. It need to play from that dragged position.
Here is my code:
public class MainActivity extends Activity {
private TextView prairText;
private AssetFileDescriptor descriptor;
private SeekBar seekBar;
private MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Keep screen active
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
init();
// Play prayer
/*if (mp != null) {
mp.start();
}*/
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mp != null && fromUser) {
mp.seekTo(progress * 1000);
}
}
});
findViewById(R.id.play_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.start();
final Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(mp != null){
int mCurrentPosition = mp.getCurrentPosition() / 1000;
seekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
findViewById(R.id.pauseButton).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.pause();
findViewById(R.id.pauseButton).setVisibility(View.INVISIBLE);
findViewById(R.id.play_button).setVisibility(View.VISIBLE);
}
mp.pause();
}
});
findViewById(R.id.restart_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.seekTo(0);
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
private void init() {
prairText = (TextView) findViewById(R.id.prairText);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
try {
descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
seekBar.setMax(mp.getDuration());
}
How to resolve this issue. Thanks in advance..
Here I did tricks:
Moved MediaPlayer instance to init() method
Changed this line
int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
to:
int mCurrentPosition = mp.getCurrentPosition();
Changed this line
mp.seekTo(progress * 1000);
to:
mp.seekTo(progress);
Finally working Code will be:
public class MainActivity extends Activity {
private TextView prairText;
private AssetFileDescriptor descriptor;
private SeekBar seekBar;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Keep screen active
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
init();
// Play song
if (mp != null) {
mp.start();
}
final Handler mHandler = new Handler();
//Make sure you update Seek bar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(mp != null){
int mCurrentPosition = mp.getCurrentPosition();
seekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mp != null && fromUser) {
mp.seekTo(progress);
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
findViewById(R.id.play_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
findViewById(R.id.pauseButton).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.pause();
findViewById(R.id.pauseButton).setVisibility(View.INVISIBLE);
findViewById(R.id.play_button).setVisibility(View.VISIBLE);
}
mp.pause();
}
});
findViewById(R.id.restart_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.seekTo(0);
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
private void init() {
mp = new MediaPlayer();
mp.reset();
prairText = (TextView) findViewById(R.id.prairText);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
try {
descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
int duration = mp.getDuration();
seekBar.setMax(duration);
}
}
Note: Don't forget to put mysong.mp3 in assets folder
I am trying to show the subtitle from the .srt file. (For Android 4.1+)
Both mp4 file and srt file exist in the device.
public class MainActivity extends Activity implements SurfaceHolder.Callback, OnPreparedListener{
MediaPlayer mediaPlayer;
SurfaceHolder surfaceHolder;
SurfaceView playerSurfaceView;
TextView tv_subtitle;
String videoSrc = Environment.getExternalStorageDirectory().getPath() + "/video.mp4";
String subTitleSrc = Environment.getExternalStorageDirectory().getPath() + "/sub.srt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playerSurfaceView = (SurfaceView)findViewById(R.id.playersurface);
tv_subtitle = (TextView)findViewById(R.id.tv_subtitle);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(videoSrc);
mediaPlayer.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
#Override
public void onTimedText(final MediaPlayer mediaPlayer, final TimedText timedText) {
if (timedText != null) {
Log.d("test", "subtitle: " + timedText.getText());
}
}
});
mediaPlayer.addTimedTextSource(subTitleSrc, MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
}
Layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SurfaceView
android:id="#+id/playersurface"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:layout_gravity="center"
android:id="#+id/tv_subtitle"
android:textColor="#android:color/holo_red_dark"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
OnTimedTextListener is not being called. My Target SDK is 22 and my devices are above Android 4.1
Am I missing anything?
I found the Answer.
Credit: Looking for a working example of addTimedTextSource for adding subtitle to a video from an .srt file in Android 4.1
mediaPlayer.selectTrack() method was missing in my code.
Here's the complete code:
public class MainActivity extends Activity implements SurfaceHolder.Callback, OnPreparedListener{
MediaPlayer mediaPlayer;
SurfaceHolder surfaceHolder;
SurfaceView playerSurfaceView;
TextView tv_subtitle;
String videoSrc = Environment.getExternalStorageDirectory().getPath() + "/video.mp4";
String subTitleSrc = Environment.getExternalStorageDirectory().getPath() + "/sub.srt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playerSurfaceView = (SurfaceView)findViewById(R.id.playersurface);
tv_subtitle = (TextView)findViewById(R.id.tv_subtitle);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(videoSrc);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepare();
mediaPlayer.addTimedTextSource(subTitleSrc, MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
int textTrackIndex = findTrackIndexFor(
MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT, mediaPlayer.getTrackInfo());
if (textTrackIndex >= 0) {
mediaPlayer.selectTrack(textTrackIndex);
} else {
Log.w("test", "Cannot find text track!");
}
mediaPlayer.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
#Override
public void onTimedText(final MediaPlayer mediaPlayer, final TimedText timedText) {
if (timedText != null) {
Log.d("test", "subtitle: " + timedText.getText());
}
}
});
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
}
}
private int findTrackIndexFor(int mediaTrackType, MediaPlayer.TrackInfo[] trackInfo) {
int index = -1;
for (int i = 0; i < trackInfo.length; i++) {
if (trackInfo[i].getTrackType() == mediaTrackType) {
return i;
}
}
return index;
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
}
I am a Android newbie. I want to design my personal videoplayer to play streaming music, so I use MediaPlayer and SurfaceView. The project plays streaming video successfully, but it can't be setloop. I have google many articles and read Android Developer. I can't figure out why mediaPlayer.setLooping(true) don't work here. Thanks^^
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
The code includes two parts: 1.Test_Videoplayer.java 2.Player.java
1.Test_Videoplayer.java
public class Test_Videoplayer extends Activity {
private SurfaceView surfaceView;
private Button btnPause, btnPlayUrl, btnStop;
private SeekBar skbProgress;
private Player player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView1);
btnPlayUrl = (Button) this.findViewById(R.id.btnPlayUrl);
btnPlayUrl.setOnClickListener(new ClickEvent());
btnPause = (Button) this.findViewById(R.id.btnPause);
btnPause.setOnClickListener(new ClickEvent());
btnStop = (Button) this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(new ClickEvent());
skbProgress = (SeekBar) this.findViewById(R.id.skbProgress);
skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
player = new Player(surfaceView, skbProgress);
}
class ClickEvent implements OnClickListener {
#Override
public void onClick(View arg0) {
if (arg0 == btnPause) {
player.pause();
} else if (arg0 == btnPlayUrl) {
String url = "http://sites.google.com/site/ronforwork/Home/android-2/littleMonster.3gp";
player.playUrl(url);
} else if (arg0 == btnStop) {
player.stop();
}
}
}
class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
int progress;
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
this.progress = progress * player.mediaPlayer.getDuration()
/ seekBar.getMax();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.mediaPlayer.seekTo(progress);
}
}
}
2.Player.java <-- here is mediaPlayer.setLooping(true)
public class Player implements OnBufferingUpdateListener, OnCompletionListener,
MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
private int videoWidth;
private int videoHeight;
public MediaPlayer mediaPlayer;
private SurfaceHolder surfaceHolder;
private SeekBar skbProgress;
private Timer mTimer = new Timer();
public Player(SurfaceView surfaceView, SeekBar skbProgress) {
this.skbProgress = skbProgress;
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mTimer.schedule(mTimerTask, 0, 1000);
}
TimerTask mTimerTask = new TimerTask() {
#Override
public void run() {
if (mediaPlayer == null)
return;
if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
handleProgress.sendEmptyMessage(0);
}
}
};
Handler handleProgress = new Handler() {
public void handleMessage(Message msg) {
int position = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (duration > 0) {
long pos = skbProgress.getMax() * position / duration;
skbProgress.setProgress((int) pos);
}
};
};
public void play() {
mediaPlayer.start();
}
public void playUrl(String videoUrl) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void pause() {
mediaPlayer.pause();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.e("mediaPlayer", "surface changed");
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnPreparedListener(this);
} catch (Exception e) {
Log.e("mediaPlayer", "error", e);
}
Log.e("mediaPlayer", "surface created");
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.e("mediaPlayer", "surface destroyed");
}
#Override
public void onPrepared(MediaPlayer arg0) {
videoWidth = mediaPlayer.getVideoWidth();
videoHeight = mediaPlayer.getVideoHeight();
if (videoHeight != 0 && videoWidth != 0) {
arg0.start();
}
Log.e("mediaPlayer", "onPrepared");
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
skbProgress.setSecondaryProgress(bufferingProgress);
int currentProgress = skbProgress.getMax()
* mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
Log.e(currentProgress + "% play", bufferingProgress + "% buffer");
}
}