Mediaplayer current position is always zero - android

I am building a simple music app.
Regardless of what I try, I can not get a song to stop in order to play a new song. I tried stop, release, stop, and release together; I created a service; I even tried to use current position to get the position of the MP3 and consider it playing if the position is > 1.
But nothing worked and I am going mad trying to figure this out.
I worked on this for 5 days and have failed at everything I have thrown at it.
I would greatly appreciate any advice and a clear solution.
I am a noob and I am trying very hard to solve my own problems but this one just has me stumped.
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.IOException;
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer mediaplayer;
mediaplayer = new MediaPlayer();
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
String extRec = intent.getExtras().getString("extRec");
Log.d("My Service", "Received extra: " + extRec);
if (mediaplayer.isPlaying()){
Log.d("My Service is playing ", "yes");
}
else {
Log.d("My Service is playing ", "no");
}
//mediaplayer.stop();
//mediaplayer.release();
try {
final String AudioURL = extRec;
Log.d("My Service audioURL ", AudioURL);
mediaplayer.setDataSource(AudioURL);
mediaplayer.prepare();
Log.d("My Service", "position: " + mediaplayer.getCurrentPosition() );
mediaplayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
return START_STICKY;
}
}

User Media Controller will help you:
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) {
//the MediaController will hide after 3 seconds - tap the screen to make it appear again
mediaController.show();
return false;
}
//--MediaPlayerControl methods----------------------------------------------------
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();
}
});
}
}
For good playing feature use Exoplayer

Related

How to get duration of audio from service and set to seekbar item in adapter?

I am trying to play an audio using service and update seekbar item in adapter. But I am unable to get duration of audio from service. Also when scrolling recyclerview, more than one item view is updated instead of updating currently playing seekbar item. I have tried below code.
public class LocalService extends Service {
boolean mBound = false;
private final IBinder mBinder = new LocalBinder();
private String path = "";
private int timer;
private static MediaPlayer mediaPlayer = new MediaPlayer();
// Random number generator
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* method for clients
*/
public int getTotalTime() {
return mediaPlayer.getDuration();
}
public int getDuration() {
// Log.v("player duration",timer+"");
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
Log.v("playing", (mediaPlayer.getCurrentPosition() / 1000) + "");
return mediaPlayer.getCurrentPosition() / 1000;
} else {
//Log.v("not playing", (mediaPlayer.getCurrentPosition() / 1000) + "");
return 0;
}
}catch (IllegalStateException i)
{
i.printStackTrace();
return 0;
}
catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
#Override
public void onCreate() {
super.onCreate();
try {
mediaPlayer = new MediaPlayer();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setAudio(String path)
{
try {
mediaPlayer.setDataSource(path);
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void playAudio() {
Log.v("audio path", path);
try {
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.prepareAsync();
mediaPlayer.start();
timer=mediaPlayer.getDuration();
Log.v("total timer1",timer+"");
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
timer=0;
mediaPlayer.stop();
mediaPlayer.reset();
//mediaPlayer.release();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void unbindService(ServiceConnection conn) {
super.unbindService(conn);
mediaPlayer.reset();
mediaPlayer.release();
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.reset();
mediaPlayer.release();
}
Service is started from adapter constructor.
Intent intent = new Intent(mContext, LocalService.class);
mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
player item click in recycler adpater
vhItemHolder.playPauseImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentlyPlayingPosition = position;
if (mBound) {
Log.v("service","bound");
//Make sure you update Seekbar on UI thread
mService.setAudio(audioDirectory+messageArrayList.get(position).getmMediaValue());
mPlayer=new MediaPlayer();
try {
mPlayer.setDataSource(audioDirectory+messageArrayList.get(position).getmMediaValue());
mPlayer.prepareAsync();
vhItemHolder.seekBar.setMax(mPlayer.getDuration());
} catch (IOException e) {
e.printStackTrace();
}
mService.playAudio();
Log.v("duration",(mService.getTotalTime())+"");
vhItemHolder.seekBar.setMax(mService.getTotalTime());
mHandler.removeCallbacks(null);
mHandler=new Handler();
((DoctorActivity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
num = mService.getDuration();
Log.v("progress",num+"");
vhItemHolder.seekBar.setProgress((num));
vhItemHolder.runningTimerTextView.setText(convertMilliToMinutes((long)mService.getDuration()));
mHandler.postDelayed(this, 50);
}
});
}
else
{
Log.v("service","not bound");
}
Inside your adapter class:
You are making a new object of MediaPlayer (mPlayer) in viewHolder's playPauseImageView's onClickListener and calling setDataSource() method on it which sets data source for this local mPlayer object not to the mediaPlayer object of your LocalService class.
Calling mService.playAudio() and mService.getDuration() methods access your LocalService class' mediaPlayer object for which setDataSource() method is not called yet, hence must be returning wrong duration and unable to play.
You should make a change in your adapter class like below:
vhItemHolder.playPauseImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentlyPlayingPosition = position;
if (mBound) {
Log.v("service","bound");
//Make sure you update Seekbar on UI thread
mService.setAudio(audioDirectory+messageArrayList.get(position).getmMediaValue());
mPlayer = mService.mediaPlayer;// or mPlayer = LocalService.mediaPlayer; as being static object.
//rather new MediaPlayer();
try {
mPlayer.setDataSource(audioDirectory+messageArrayList.get(position).getmMediaValue());
mPlayer.prepareAsync();
vhItemHolder.seekBar.setMax(mPlayer.getDuration());
} catch (IOException e) {
e.printStackTrace();
}
mService.playAudio();
Log.v("duration",(mService.getTotalTime())+"");
vhItemHolder.seekBar.setMax(mService.getTotalTime());
mHandler.removeCallbacks(null);
mHandler=new Handler();
((DoctorActivity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
num = mService.getDuration();
Log.v("progress",num+"");
vhItemHolder.seekBar.setProgress((num));
vhItemHolder.runningTimerTextView.setText(convertMilliToMinutes((long)mService.getDuration()));
mHandler.postDelayed(this, 50);
}
});
}
else
{
Log.v("service","not bound");
}

Cant play a song using MediaPlayer

Im having some problems playing a simple song (stored in the external SD) using MediaPlayer API. I really dont know what Im doing wrong, cause I havent seen the code error in any other questions and using the developer I havent found it either.
The error Im getting is this:
08-25 00:20:49.514: D/MediaPlayer(26764): mPlayerID = 94
08-25 00:20:49.519: E/MediaPlayer(26764): error (1, -2147483648)
08-25 00:20:49.597: E/MediaPlayer(26764): Error (1,-2147483648)
AudioActivity.java
public class AudioActivity extends Activity{
Audio audioPlayer;
public AudioActivity(){
audioPlayer = new Audio();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set of view where videos and the listView (is there is any) will appear
setContentView(R.layout.audio_player);
Button play = (Button)findViewById(R.id.playButton);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory() + "/" + "song";
audioPlayer.loadFile(path);
audioPlayer.prepare();
audioPlayer.play();
}
});
Button pauseResume = (Button)findViewById(R.id.pauseButton);
pauseResume.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
audioPlayer.pause();
}
});
Button stop = (Button)findViewById(R.id.stopButton);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
audioPlayer.stop();
}
});
}
}
Audio.class
public class Audio {
MediaPlayer mediaPlayer;
String pathSong;
public Audio(){
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
Log.d("Error", "Arg1: " + arg1 + ".Arg2: " + arg2);
mediaPlayer.reset();
return false;
}
});
}
public void loadFile(String path){
try {
mediaPlayer.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void prepare(){
try {
mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void play(){
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
public void stop(){
mediaPlayer.stop();
}
public void pause(){
mediaPlayer.pause();
}
public int getDuration(){
return mediaPlayer.getDuration();
}
public MediaPlayer getMediaPlayer(){
return mediaPlayer;
}
public TrackInfo[] getTrackInfo(){
return mediaPlayer.getTrackInfo();
}
}
Any idea? Why the code (1, -2147483648) doesnt appear anywhere? Thanks!

Android: Starting a service to play radio channels

I am trying to make a service that plays in background which is unbounded. I have walked myself through some of the example codes on the internet but I can't get my application to play the radio when I'm calling the service class.
Please have a look at the code and tell me where I am going wrong... When I call MyService class from ArmanFMRadio onClick It toasts "My Service Created" & "My Service Started" but doesnt get to play the audio for the radio stream link. I've checked it otherwise and the link seems fine, so problem lies somewhere in the code to my understanding:
package com.etc.etcc;
public class ArmanFMRadio extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.armanfm);
initializeUIElements();
//initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setVisibility(View.VISIBLE);
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonPlay:
playSeekBar.setVisibility(View.VISIBLE);
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
startService(new Intent(this, MyService.class));
//startPlaying();
break;
case R.id.buttonStopPlay:
stopPlaying();
break;
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Just look at onClick on the above code, because this class works fine to my thinking.
MyService class:
package com.etc.etcc;
public class MyService extends Service {
private static final String TAG = "MyService";
private MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
onStart is deprecated method. you should use onStartCommand method.
Debug your code and check weather there is any Exception or something
Also you are using the service so possible that you service will call twice in that case your onStartCommand method will be called twice so there you will have to check the startId which you will get as a parameter. If startId > 1 that means previously your service is started so you can stop media player and again start a media player with latest source or you can just ignore the second request.
If you are not confidence with service you can put your code in the activity and check weather your code is working fine or not after that you can replace this code in the service.

How do I play a live HTTP audio stream in MediaPlayer on Android?

I want to play a live HTTP stream in my Android app, so I installed the Windows Media Encoder 9 on another PC on the same LAN, and used it to create a live HTTP audio stream.
The live HTTP stream is okay: I tested it, and it can be played by Windows Media Player or VLC on a PC, and can be played by VLC for Android on my mobile.
So, in my Android app, I wrote this code:
private MediaPlayer player = null;
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
//.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button)findViewById(R.id.play);
address = (TextView)findViewById(R.id.address);
btnPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
play();
}
});
}
private void play()
{
String serverIp;
serverIp = address.getText().toString(); // get the uri address, for example http://xxx.xxx.xxx.xxx:2340
if (player == null)
{
player = new MediaPlayer();
}
else
{
player.stop();
player.reset();
}
try {
Log.v("", "Init a new MediaPlayer");
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.v("", "Set the stream type to STREAM_MUSIC");
player.setDataSource(this, Uri.parse(serverIp));
Log.v("", "Set the source is " + serverIp);
player.setOnBufferingUpdateListener(this);
player.setOnPreparedListener(this);
player.setOnErrorListener(this);
player.prepareAsync();
Log.v("", "After prepareAsync");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.v("IllegalArgumentException", e.toString());
} catch (SecurityException e) {
// TODO Auto-generated catch block
Log.v("SecurityException", e.toString());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Log.v("IllegalStateException", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v("IOException", e.toString());
} catch (Exception e) {
Log.v("Exception",e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
Log.v("onPrepared", "After prepareAsync");
mp.start();
}
catch (Exception e) {
Log.v("play", e.toString());
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// TODO Auto-generated method stub
Log.v("onBufferingUpdate", "Buffering Update");
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Log.v("MediaPlayer onError", "what=" + what + " extra=" + extra);
return true;
}
But it didn’t work. When I click the play button, nothing happens. But if I input some other URL I found on the internet (for example, http://www.example.com/song.mp3), it works.
So can anyone help me? The Log info is below. My mobile is HTC s710e, and my Android version is 4.0.4.
11-20 22:28:14.137: V/(580): Init a new MediaPlayer
11-20 22:28:14.137: V/(580): Set the stream type tp STREAM_MUSIC
11-20 22:28:14.147: D/MediaPlayer(580): Couldn't open file on client side, trying server side
11-20 22:28:14.178: E/Trace(39): error opening trace file: No such file or directory (2)
11-20 22:28:14.178: V/(580): After prepareAsync
11-20 22:28:14.297: V/ChromiumHTTPDataSource(39): connect on behalf of uid 10044
11-20 22:28:14.339: I/qtaguid(39): Tagging socket 27 with tag 3f500000000(1013) for uid 10044 failed errno=-2
11-20 22:28:14.629: I/ChromiumHTTPDataSourceSupport(39): Server responded with http status 400
11-20 22:28:14.648: I/qtaguid(39): Untagging socket 27 failed errno=-2
11-20 22:28:14.657: I/AwesomePlayer(39): mConnectingDataSource->connect() returned -1004
11-20 22:28:14.657: E/MediaPlayer(580): error (1, -1004)
11-20 22:28:14.667: E/MediaPlayer(580): Error (1,-1004)
11-20 22:28:14.667: V/MediaPlayer onError(580): what=1 extra=-1004
you can play HLS on android 3.0and 3.0 + version, older versions doesnt support HLS. This code below, can work on 3.0 + version. To play video all android version you have to use rtsp streaming or http prograssive download.
Player class
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class VideoPlayerActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static final String TAG = "MediaPlayerDemo";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private Bundle extras;
private static final String MEDIA = "media";
private static final int STREAM_VIDEO = 5;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPreview = (SurfaceView) findViewById(R.id.VideoView);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo(Integer Media) {
doCleanUp();
try {
path = "http://www.pocketjourney.com/downloads/pj/video/famous.3gp";
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
//mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(STREAM_VIDEO);
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
Main XML
<VideoView
android:id="#+id/VideoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="1"/>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:layout_weight="1" android:background="#aaaaaa">
</LinearLayout>
</LinearLayout>
And you have to add to your manifest internet permission
uses-permission android:name="android.permission.INTERNET" />

muting one audio and playing other audio in its place (VideoView)

package z.x;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
public class AsdqweActivity extends Activity {
/** Called when the activity is first created. */
VideoView myVideoView;
TextView translation;
String SrcPath = "/sdcard/bunny.MP4",txtdisplay="";
Thread Thread1,Thread2;
Button tag;
int count=0,tstart=-1,tend=0;
AudioManager am;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myVideoView = (VideoView) findViewById(R.id.newVideoView);
translation= (TextView) findViewById(R.id.translation);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(myVideoView);
myVideoView.setMediaController(mediaController);
myVideoView.setKeepScreenOn(true);
Runnable runnable = new VideoPlayer();
Thread2= new Thread(runnable);
Thread2.start();
runnable = new CountDownRunner();
Thread1= new Thread(runnable);
Thread1.start();
runnable = new AudioPlayer();
Thread1= new Thread(runnable);
Thread1.start();
am =
tag = (Button) findViewById(R.id.start);
tag.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//how to change the text on the button????????
if(count%2==0)
{
tstart=myVideoView.getCurrentPosition();
System.out.println("tag starts here: "+ tstart);
myVideoView.pause();
tend=tstart+1000;
count++;
if((tstart+1000)>myVideoView.getDuration())
{
tend=myVideoView.getDuration();
count++;
}
}
else
{
tend = myVideoView.getCurrentPosition();
if(tend>=(tstart+1000)){
System.out.println("tag ends here: "+ tend);
count++;
myVideoView.pause();
}
else
{
System.out.println("invalid tagging");
}
tstart=-1;
}
}
});
myVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
Log.v("log_tag", "On Completion");
try {
Thread1.join();
Thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//r.stopThread();
finish();
}
});
}
class VideoPlayer implements Runnable{
public void run()
{
myVideoView.requestFocus();
myVideoView.setVideoPath(SrcPath);
myVideoView.start();
}
}
class AudioPlayer implements Runnable{
public AudioPlayer() {
// TODO Auto-generated constructor stub
}
public void run()
{
/*myVideoView.setsetvolume(0,0);
audio.requestFocus();
audio.setVideoPath(SrcPathaudio);
audio.start();*/
}
}
class CountDownRunner implements Runnable
{
File file = new File("/sdcard/harsh.srt");
long r=0;
RandomAccessFile rand;
public CountDownRunner() {
// TODO Auto-generated constructor stub
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try {
rand = new RandomAccessFile(file,"r");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
translation = (TextView)findViewById(R.id.translation);
}
public void run()
{
// Get the object of DataInputStream
while(!Thread.currentThread().isInterrupted())
{
try
{
doWork();
Thread.sleep(100);
}catch (InterruptedException e)
{
Thread.currentThread().interrupt();
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
closeRandFile();
}
public void closeRandFile(){
try {
rand.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doWork(){
runOnUiThread(new Runnable() {
public void run() {
try{
rand.seek(r);
//If it returns milliseconds, divide by 1000
int playTime = myVideoView.getCurrentPosition();
long t1=0,t2=0;
int i=0,j=0;
/* String textValue = "i havent entered it yet";
System.out.println(playTime);
if(playTime<15000){
textValue = "its still not 15000";
System.out.println(textValue);
}else if(playTime>3000)
{textValue = "its more than 15000";}*/
////////////////////////////////////
try{
// Open the file that is the first
// command line parameter
String strLine;
//Read File Line By Line
while(((strLine = rand.readLine()) != null)&&((strLine=="")))
{
System.out.println(strLine+" line 184");
}
if(strLine != null)
{
i = Integer.parseInt(strLine);
System.out.println(strLine+" line 189");
if(i>j){
if((strLine = rand.readLine()) != null)
{
//02:03:24,100 --> 02:03:25,500
//String substring(int startIndex, int endIndex)
int h =Integer.parseInt(strLine.substring(0,2));
int m =Integer.parseInt(strLine.substring(3,5));
int s =Integer.parseInt(strLine.substring(6,8));
int ms=Integer.parseInt(strLine.substring(9,12));
t1 = (((((h*60)+m)*60)+s)*1000)+ms ;
System.out.println("start of this text time "+t1);
int l = strLine.indexOf("-->")+4;
h =Integer.parseInt(strLine.substring(l+0,l+2));
m =Integer.parseInt(strLine.substring(l+3,l+5));
s =Integer.parseInt(strLine.substring(l+6,l+8));
ms=Integer.parseInt(strLine.substring(l+9,l+12));
t2 = (((((h*60)+m)*60)+s)*1000)+ms ;
System.out.println("end of this text time "+t2);
}
if((playTime<=t2)&&(playTime>=t1)){
while (((strLine = rand.readLine()) != null)&&(strLine!="")){
// Print the content on the console
txtdisplay=txtdisplay+strLine;
}
System.out.println(txtdisplay);
r=rand.getFilePointer();
translation.setText(txtdisplay);
}
txtdisplay="";
}
}
//Close the input stream
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
//////////////////////////////////////
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
I am new here. I was asked by my professor to play other audio while the same video is being played(for example a person doesn't understand English and wants the the app to play french ). I have used video view. One possible method was to mute the present audio and play the french audio stored in my sdcard. but video view supports no muting( i couldn't find one). I read that i have to go for media player instead of video view.
Please help...!! what should i do... Thanks in advance.
if you want to get access to the MediaPlayer of a VideoView you have to call MediaPlayer.OnPreparedListener and MediaPlayer.OnCompletionListener, then you can call setVolume(0f, 0f); function to set the volume to 0.
Do this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
VideoView videoView = (VideoView)this.findViewById(R.id.VVSimpleVideo);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
videoView.setMediaController(mc);
String _path = "/mnt/sdcard/Movies/video5.mp4";
videoView.setVideoPath(_path);
videoView.setOnPreparedListener(PreparedListener);
videoView.requestFocus();
//Dont start your video here
//videoView.start();
}
MediaPlayer.OnPreparedListener PreparedListener = new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer m) {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
m.setVolume(0f, 0f);
m.setLooping(false);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};

Categories

Resources