I am trying to set a video playing in a VideoView to a specified position, but there's no method like setCurrentPosition. What should I use?
Try using seekTo
private VideoView mVideoView;
private boolean mShouldStop = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVideoView = (VideoView) findViewById(R.id.myvideoview);
mVideoView.setVideoPath("/storage/emulated/0/Android/data/com.example.android.camera2video/files/a.mp4");
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
mVideoView.seekTo(6000);
mVideoView.start();
trackProgress();
}
private void trackProgress() {
new Thread(new Runnable() {
#Override
public void run() {
while (!mShouldStop) {
if (mVideoView != null && mVideoView.isPlaying()) {
if (mVideoView.getCurrentPosition() >= 12000) {
mVideoView.stopPlayback();
mShouldStop = true;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
Related
in my app i want to offer the user a option to set an animation as live wallpaper using WallpaeprService, also my app include a Radio player (playing in the backgroud) if app is open so you can navigate in other apps while music is playing.
my problem :
if live wallpaper is working and user try to close the app by (Swipe to exit / Recent Task),the music keeps playing although app is closed.
i tried to stop music like this ,but doesn't work :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#SuppressLint({"CommitPrefEdits", "Assert"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, KillNotificationService.class));
trackSelector = new DefaultTrackSelector();
loadControl = new DefaultLoadControl();
exoPlayer = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(getApplicationContext()), trackSelector, loadControl);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (Build.VERSION.SDK_INT > 15) {
if (started && MusicButton.isChecked()) {
started = false;
exoPlayer.setPlayWhenReady(false);
MusicButton.setChecked(true);
releaseAudioFocusForMyApp(MainActivity.this);
} else {
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
if (gotFocus) {
started = true;
exoPlayer.setPlayWhenReady(true);
MusicButton.setChecked(false);
}
}
} else {
if (started && MusicButton.isChecked()) {
started = false;
mediaPlayer.pause();
MusicButton.setChecked(true);
releaseAudioFocusForMyApp(MainActivity.this);
} else {
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
if (gotFocus) {
started = true;
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
}
}
});
private void playRadio(String url) {
Uri audioUri = Uri.parse(url);
DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("ExoPlayerDemo");
ExtractorsFactory extractor = new DefaultExtractorsFactory();
MediaSource audioSource = new ExtractorMediaSource.Factory(dataSourceFactory).setExtractorsFactory(extractor).createMediaSource(audioUri);
exoPlayer.prepare(audioSource);
prepared = true;
exoPlayer.setPlayWhenReady(true);
exoPlayer.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, #Nullable Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (isPreparing && playbackState == ExoPlayer.STATE_READY) {
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
isPreparing = false;
isReady = true;
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
} catch (Exception e) {
e.printStackTrace();
}
MApplication.sBus.post(PlaybackEvent.PAUSE);
}
#Override
protected void onStart() {
super.onStart();
}
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PAUSE:
if (Build.VERSION.SDK_INT > 15) {
if (exoPlayer.getPlayWhenReady()) {
exoPlayer.setPlayWhenReady(false);
MusicButton.setChecked(true);
}
} else {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
MusicButton.setChecked(true);
}
}
break;
case PLAY:
if (Build.VERSION.SDK_INT > 15) {
if (!exoPlayer.getPlayWhenReady()) {
exoPlayer.setPlayWhenReady(true);
MusicButton.setChecked(false);
}
} else {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
break;
}
}
#Override
public void onPause() {
super.onPause();
}
}
}
problem solved by checking if live wallpaper are running in the backgroud or not:
#Override
protected void onDestroy() {
super.onDestroy();
try {
WallpaperManager wpm = WallpaperManager.getInstance(this);
WallpaperInfo info = wpm.getWallpaperInfo();
if (info != null && info.getPackageName().equals(this.getPackageName())) {
/*stop music*/
} else {
Log.d(TAG, "We're not running");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I'm trying to create a small application which both retrieves depth data and shows a little "preview" from my RGB camera.
Here's the code of my MainScreen class:
private static final String TAG = MainScreen.class.getSimpleName();
public static TangoConfig mConfig;
public static Tango mTango;
public TangoCameraPreview preview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
preview = new TangoCameraPreview(this);
ViewGroup layout = (ViewGroup)findViewById(R.id.content_main_screen);
layout.addView(preview);
}
#Override
protected void onDestroy() {
super.onDestroy();
preview.disconnectFromTangoCamera();
mTango.disconnect();
}
#Override
protected void onPause() {
super.onPause();
preview.onPause();
synchronized (this) {
try {
mTango.disconnect();
} catch (TangoErrorException e) {
Log.e(TAG, getString(R.string.exception_tango_error), e);
}
}
}
#Override
protected void onResume() {
super.onResume();
mTango = new Tango(MainScreen.this, new Runnable() {
#Override
public void run() {
synchronized (MainScreen.this) {
try {
mConfig = setupTangoConfig(mTango);
mTango.connect(mConfig);
preview.connectToTangoCamera(mTango, TangoCameraIntrinsics.TANGO_CAMERA_COLOR);
startupTango();
} catch (TangoOutOfDateException e) {
Log.e(TAG, getString(R.string.exception_out_of_date), e);
} catch (TangoErrorException e) {
Log.e(TAG, getString(R.string.exception_tango_error), e);
} catch (TangoInvalidException e) {
Log.e(TAG, getString(R.string.exception_tango_invalid), e);
}
}
}
});
preview.onResume();
}
private TangoConfig setupTangoConfig(Tango tango) {
TangoConfig config = tango.getConfig(TangoConfig.CONFIG_TYPE_DEFAULT);
config.putBoolean(TangoConfig.KEY_BOOLEAN_LOWLATENCYIMUINTEGRATION, true);
config.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, true);
config.putInt(TangoConfig.KEY_INT_DEPTH_MODE, TangoConfig.TANGO_DEPTH_MODE_POINT_CLOUD);
return config;
}
private void startupTango() {
final ArrayList<TangoCoordinateFramePair> framePairs =
new ArrayList<TangoCoordinateFramePair>();
mTango.connectListener(framePairs, new Tango.OnTangoUpdateListener() {
#Override
public void onPoseAvailable(final TangoPoseData pose) {
// We are not using TangoPoseData for this application.
}
#Override
public void onXyzIjAvailable(TangoXyzIjData xyzIj) {
// We are not using onXyzIjAvailable for this app.
}
#Override
public void onPointCloudAvailable(final TangoPointCloudData pointCloudData) {
logPointCloud(pointCloudData);
}
#Override
public void onTangoEvent(final TangoEvent event) {
// Ignoring TangoEvents.
}
#Override
public void onFrameAvailable(int cameraId) {
if(cameraId == TangoCameraIntrinsics.TANGO_CAMERA_COLOR) {
preview.onFrameAvailable();
}
}
});
}
private void logPointCloud(TangoPointCloudData pointCloudData) {
Log.i(TAG, String.format(getString(R.string.log_pointcloud_data),
pointCloudData.numPoints,
calculateAveragedDepth(pointCloudData.points, pointCloudData.numPoints)));
}
private float calculateAveragedDepth(FloatBuffer pointCloudBuffer, int numPoints) {
float totalZ = 0;
float averageZ = 0;
if (numPoints != 0) {
int numFloats = 4 * numPoints;
for (int i = 2; i < numFloats; i = i + 4) {
totalZ = totalZ + pointCloudBuffer.get(i);
}
averageZ = totalZ / numPoints;
}
return averageZ;
}
When I start this code, the TangoCameraPreview stays empty, and the onFrameAvailable()-Method is never called.
I have included Camera persmissions in my Android manifest xml, but it still isn't calling the handler.
Sadly, I haven't found any good tutorials on this topic, and since this is just a first step in my project, I don't want to write my own renderer just yet, if at all.
What could be the problem?
after startup Tango make a call to 'connectTextureId':
tango.ConnectTextureId(TangoCameraIntrinsics.TangoCameraColor, -1);
Introduction
I have a Server in Java that send video packets by packets in TCP to an Android Client.
In Android Client side, i have a class : DowloadVideo that receive packets of the Java Server and a Thread that launch the media player with the video.
Problem
My problem is that when i launch the video after 5s of receive packets, the media player read only the receipt packets at the moment when the media player launch.
Receive packets by the client continue..
But the media player can not read more of packets continues.
Code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
vidSurface = (SurfaceView) findViewById(R.id.surfView);
ConcurrentLinkedDeque<OutputStream[]> list = new ConcurrentLinkedDeque<>();
Connexion connexion = new Connexion(list);
connexion.execute();
new Thread(new Task2(list)).start();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(vidHolder);
mediaPlayer.setDataSource(vidAddress);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.seekTo(1000);
mediaPlayer.start();
}
});
}
private class Connexion extends AsyncTask<Void, Void, Void> {
private ConcurrentLinkedDeque<OutputStream[]> list;
public Connexion(ConcurrentLinkedDeque<OutputStream[]> list) {
this.list = list;
}
#Override
protected Void doInBackground(Void... params) {
ConcurrentLinkedDeque<OutputStream[]> list = new ConcurrentLinkedDeque<>();
DownloadVideo dv = new DownloadVideo(list);
dv.connexion();
return null;
}
}
public void launchVideo() {
// Chemin de la vidéo
try {
Thread.sleep(5000);
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Movies/chrono2.mp4");
Long max = file.length();
vidHolder = vidSurface.getHolder();
vidHolder.addCallback(this);
} catch (ActivityNotFoundException e2) {
// displayToast(getResources().getString(R.string.error_unknownMX)); // Erreur, on affiche un message à l'utilisateur
// Log.e( "Error", getResources().getString(R.string.error_unknownMX));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void displayToast(String message) {
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
toast.show();
}
// Thread to read video
class Task2 implements Runnable {
private ConcurrentLinkedDeque<OutputStream[]> list;
public Task2(ConcurrentLinkedDeque<OutputStream[]> list) {
this.list = list;
}
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
Log.d("1", "Thread2");
launchVideo();
}
});
}
}
Thanks.
Excuse me.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
vidSurface = (SurfaceView) findViewById(R.id.surfView);
ConcurrentLinkedDeque<OutputStream[]> list = new ConcurrentLinkedDeque<>();
Connexion connexion = new Connexion(list);
connexion.execute();
new Thread(new Task2(list)).start();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(vidHolder);
mediaPlayer.setDataSource(vidAddress);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
private class Connexion extends AsyncTask<Void, Void, Void> {
private ConcurrentLinkedDeque<OutputStream[]> list;
public Connexion(ConcurrentLinkedDeque<OutputStream[]> list) {
this.list = list;
}
#Override
protected Void doInBackground(Void... params) {
ConcurrentLinkedDeque<OutputStream[]> list = new ConcurrentLinkedDeque<>();
DownloadVideo dv = new DownloadVideo(list);
dv.connexion();
return null;
}
}
public void launchVideo() {
vidHolder = vidSurface.getHolder();
vidHolder.addCallback(this);
}
// Thread to read video
class Task2 implements Runnable {
private ConcurrentLinkedDeque<OutputStream[]> list;
public Task2(ConcurrentLinkedDeque<OutputStream[]> list) {
this.list = list;
}
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
Log.d("1", "Thread2");
launchVideo();
}
});
}
}
public class camera extends Activity {
private static final String LOG_TAG = "photo";
private int cameraId = 1;
private Camera camera = null;
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_photo);
}
public void takephoto() {
camera.takePicture(null, null, pictureCallback);
}
#Override
public void onResume() {
Log.d(LOG_TAG, "onResume");
super.onResume();
setSurface();
}
private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
FileOutputStream jpg = new FileOutputStream(String.format(
"/sdcard/%d.jpg", System.currentTimeMillis()));
jpg.write(data);
jpg.close();
Log.i(LOG_TAG, "written " + data.length + " bytes to /sdcard/JBCameraCapture.jpg");
} catch (Exception e) {
e.printStackTrace();
}
finish();
}
};
private SurfaceHolder.Callback shCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i(LOG_TAG, "surfaceDestroyed callback");
if (camera != null) {
camera.stopPreview();
camera.release();
}
camera = null;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.i(LOG_TAG, "surfaceCreated callback");
startCamera(cameraId);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.i(LOG_TAG, "surfaceChanged callback ");
}
};
private void setSurface() {
SurfaceView previewSurfaceView = (SurfaceView) findViewById(R.id.preview_surface);
previewSurfaceView.getHolder().addCallback(shCallback);
}
protected void startCamera(final int id) {
new AsyncTask<Integer, Void, Camera>() {
#Override
protected Camera doInBackground(Integer... ids) {
return openCamera(ids[0]);
}
#Override
protected void onPostExecute(Camera c) {
startPreview(id, c);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takephoto();
}
}, 1000);
}
}.execute(id);
}
private static Camera openCamera(int id) {
Log.d(LOG_TAG, "opening camera " + id);
Camera camera = null;
try {
camera = Camera.open(id);
Log.d(LOG_TAG, "opened camera " + id);
} catch (Exception e) {
e.printStackTrace();
camera.release();
camera = null;
}
return camera;
}
private void startPreview(int id, Camera c) {
if (c != null) {
try {
SurfaceView previewSurfaceView = (SurfaceView) findViewById(R.id.preview_surface);
SurfaceHolder holder = previewSurfaceView.getHolder();
c.setPreviewDisplay(holder);
camera = c;
cameraId = id;
} catch (IOException e) {
e.printStackTrace();
c.release();
}
}
}
}
I have written this code for the front camera but it is not working in all Android devices, in some devices it reboots the phone and in some devices it shows an unfortunate error and in some devices it works properly.
How do I pass a URL to Media player? I have this code:
public class MainActivity 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.activity_main);
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);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
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();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://radioo.cz/wplay/2850");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
But it doesn't work... How do I set the url if I want to play this (http://www.radioo.cz/wplay/2850) radio? What am I doing wrong?
I have to admit I never used this class before but from what i found here : http://developer.android.com/reference/android/media/MediaPlayer.html
Instead of using
MediaPlayer.setDataSource(Uri)
you should use
MediaPlayer.create(Context context, Uri uri)
Which would be in your case :
player.create(this,"http://www.radioo.cz/wplay/2850");
I hope this can help you.