Getting current frame from android vlc media player - android

I'm using VLC-Android in order to play H264 RTSP live stream in my android application, the following code successfully renders the stream video onto the surface view:
MediaPlayer mMediaPlayer = new MediaPlayer(VLCInstance.get());
SurfaceView mSurfaceView = (SurfaceView) findViewById(R.id.player);
final IVLCVout vlcVout = Constants.mMediaPlayer.getVLCVout();
vlcVout.detachViews();
vlcVout.setVideoView(mSurfaceView);
vlcVout.setWindowSize(mSurfaceDims.getWidth(), mSurfaceDims.getHeight());
vlcVout.attachViews();
mSurfaceView.setKeepScreenOn(true);
Media media = new Media(VLCInstance.get(), Uri.parse(path));
mMediaPlayer.setMedia(media);
mMediaPlayer.play();
VLCInstance.java:
package bi.anpr.vlc;
import android.content.Context;
import android.util.Log;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.util.VLCUtil;
public class VLCInstance {
public final static String TAG = "VLC/Util/VLCInstance";
private static LibVLC sLibVLC = null;
/** A set of utility functions for the VLC application */
public synchronized static LibVLC get() throws IllegalStateException {
if (sLibVLC == null) {
final Context context = VLCApplication.getAppContext();
if(!VLCUtil.hasCompatibleCPU(context)) {
Log.e(TAG, VLCUtil.getErrorMsg());
throw new IllegalStateException("LibVLC initialisation failed: " + VLCUtil.getErrorMsg());
}
try{
sLibVLC = new LibVLC(context);
}catch (Throwable e){
e.printStackTrace();
}
}
return sLibVLC;
}
public static synchronized void restart(Context context) throws IllegalStateException {
if (sLibVLC != null) {
sLibVLC.release();
sLibVLC = new LibVLC(context);
}
}
}
The problem is that the org.videolan.libvlc.MediaPlayer renders the video on the SurfaceView after calling play() without any event that helps you to grab the current frame on the view, where i need to get the current frame each interval of time to perform some image processing on it.
So is it possible using vlc-android-sdk to grab current frame, into a buffered image or an OpenCV Mat, while playing live streams or local video resources?
Note that it is possible with java (desktop vlcj) through the DirectMediaPlayer class.
Thanks in advance!!

I'd found a very simple an very fast solution to do this. Just use a TextureView instead of a SurfaceView, and then retrieve the image anytime while playing using the getBitmap() function as shown below.
public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener,
org.videolan.libvlc.media.MediaPlayer.OnBufferingUpdateListener,
org.videolan.libvlc.media.MediaPlayer.OnCompletionListener,
org.videolan.libvlc.media.MediaPlayer.OnPreparedListener,
org.videolan.libvlc.media.MediaPlayer.OnVideoSizeChangedListener {
private AppCompatActivity me = this;
private MediaPlayer mMediaPlayer;
private TextureView mTextureViewmTextureView;
private String mUrl = "/storage/emulated/0/videos/test.mp4";
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
mMediaPlayer = new MediaPlayer(VLCInstance.get());
mTextureViewmTextureView = (TextureView) findViewById(R.id.player);
mTextureView.setSurfaceTextureListener(this);
}
private void attachViewSurface() {
final IVLCVout vlcVout = mMediaPlayer.getVLCVout();
mMediaPlayer.setScale(0);
vlcVout.detachViews();
vlcVout.setVideoView(mTextureView);
vlcVout.setWindowSize(mTextureView.getWidth(), mTextureView.getHeight());
vlcVout.attachViews();
mTextureView.setKeepScreenOn(true);
}
private void play(String path) {
try {
Media media;
if (new File(path).exists()) {
media = new Media(VLCInstance.get(), path);
} else {
media = new Media(VLCInstance.get(), Uri.parse(path));
}
mMediaPlayer.setMedia(media);
mMediaPlayer.play();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
attachViewSurface();
if (mMediaPlayer.hasMedia())
mMediaPlayer.play();
else
play(mUrl);
}
public Bitmap getImage() {
return mTextureView.getBitmap();
}
}
VLCInstance.java:
import android.content.Context;
import android.util.Log;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.util.VLCUtil;
public class VLCInstance {
public final static String TAG = "VLC/Util/VLCInstance";
private static LibVLC sLibVLC = null;
/** A set of utility functions for the VLC application */
public synchronized static LibVLC get() throws IllegalStateException {
if (sLibVLC == null) {
final Context context = VLCApplication.getAppContext();
if(!VLCUtil.hasCompatibleCPU(context)) {
Log.e(TAG, VLCUtil.getErrorMsg());
throw new IllegalStateException("LibVLC initialisation failed: " + VLCUtil.getErrorMsg());
}
try{
sLibVLC = new LibVLC(context);
}catch (Throwable e){
e.printStackTrace();
}
}
return sLibVLC;
}
public static synchronized void restart(Context context) throws IllegalStateException {
if (sLibVLC != null) {
sLibVLC.release();
sLibVLC = new LibVLC(context);
}
}
}

Related

How to apply android system equalizer settings on MediaPlayer object?

I'm a newbie in programming and android development.
So I have a problem: all music players, such as Apple Music, Sony's Music app and other ones use system audio effects (from settings app), but my app doesn't. I don't know how to apply system audio output settings and effects on my app.
Here is my class which uses Media Player:
public class MPlayer {
private static String File = null;
private static boolean isNew = false;
private static MediaPlayer mPlayer = new MediaPlayer();
private static Equalizer mEqualizer;
public static void setFile2Play(String file){
if(!file.equals(File)){
File = file;
isNew = true;
try {
if(mPlayer != null){
mPlayer.release();
mPlayer = new MediaPlayer();
}
mPlayer.setDataSource(file);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.prepare();
mEqualizer = new Equalizer(1,mPlayer.getAudioSessionId());
mEqualizer.setEnabled(true);
}catch (IOException e){}
}
else isNew = false;
}
public static void play(){
if(isNew) {
mPlayer.start();
}
}
public static boolean isPlaying() {return mPlayer.isPlaying();}
public static void seekTo(int i){mPlayer.seekTo(i);}
public static int getCurrentPosition(){return mPlayer.getCurrentPosition();}
public static int getDuration(){return mPlayer.getDuration();}
public static void pause(){mPlayer.pause();}
public static void stop(){mPlayer.stop();}
}

javafxports how to call android native Media Player

As the javafxports Media is not yet implemented I'm looking to use the Android Native MediaPlayer instead. Does anyone know how to do this.
If you have a look at the GoNative sample here (docs and code), you'll find a way to add Android native code to your JavaFX project.
This is a simple example of adding android.media.MediaPlayer to a JavaFX project using the Gluon plugin.
Based on a Single View project, let's add first an interface with the required audio method signatures:
public interface NativeAudioService {
void play();
void pause();
void resume();
void stop();
}
Now in our View we can create the buttons to call those methods based on an instance of AndroidNativeAudio class that implements the NativeAudioService interface:
public class BasicView extends View {
private NativeAudioService service;
private boolean pause;
public BasicView(String name) {
super(name);
try {
service = (NativeAudioService) Class.forName("com.gluonhq.nativeaudio.AndroidNativeAudio").newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
System.out.println("Error " + ex);
}
if (service != null) {
final HBox hBox = new HBox(10,
MaterialDesignIcon.PLAY_ARROW.button(e -> service.play()),
MaterialDesignIcon.PAUSE.button(e -> {
if (!pause) {
service.pause();
pause = true;
} else {
service.resume();
pause = false;
}
}),
MaterialDesignIcon.STOP.button(e -> service.stop()));
hBox.setAlignment(Pos.CENTER);
setCenter(new StackPane(hBox));
} else {
setCenter(new StackPane(new Label("Only for Android")));
}
}
#Override
protected void updateAppBar(AppBar appBar) {
appBar.setNavIcon(MaterialDesignIcon.MUSIC_NOTE.button());
appBar.setTitleText("Native Audio");
}
}
Now, we create the native class under the Android folder. It will make use of the android API. It will try to find the audio file audio.mp3 that we have to place under the /src/android/assets folder:
package com.gluonhq.nativeaudio;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import java.io.IOException;
import javafxports.android.FXActivity;
public class AndroidNativeAudio implements NativeAudioService {
private MediaPlayer mp;
private int currentPosition;
public AndroidNativeAudio() { }
#Override
public void play() {
currentPosition = 0;
try {
if (mp != null) {
stop();
}
mp = new MediaPlayer();
AssetFileDescriptor afd = FXActivity.getInstance().getAssets().openFd("audio.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.setAudioStreamType(AudioManager.STREAM_RING);
mp.setOnCompletionListener(mp -> stop());
mp.prepare();
mp.start();
} catch (IOException e) {
System.out.println("Error playing audio resource " + e);
}
}
#Override
public void stop() {
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
}
#Override
public void pause() {
if (mp != null) {
mp.pause();
currentPosition = mp.getCurrentPosition();
}
}
#Override
public void resume() {
if (mp != null) {
mp.start();
mp.seekTo(currentPosition);
}
}
}
Finally, we can deploy the project to an Android device running gradlew androidInstall.
The native audio player was used in the following example:
https://gist.github.com/bgmf/d87a2bac0a5623f359637a3da334f980
Beside some prerequisites, the code looks like this:
package my.application;
import my.application.Constants;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import org.robovm.apple.avfoundation.AVAudioPlayer;
import org.robovm.apple.foundation.NSErrorException;
import org.robovm.apple.foundation.NSURL;
import org.robovm.apple.foundation.NSURLScheme;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NativeAudioServiceIOS extends PathHelperIOS implements NativeAudioService {
private static final Logger LOG = Logger.getLogger(NativeAudioServiceIOS.class.getName());
private static final String DIR_NAME = Constants.OBJECTS_BASE_PATH;
private final ReadOnlyObjectWrapper<Status> status = new ReadOnlyObjectWrapper<>(this, "status", Status.STOP);
private String filename = null;
private AVAudioPlayer player = null;
public NativeAudioServiceIOS() {
super();
}
#Override
public void init(String filename) throws NativeServiceException {
this.filename = filename.startsWith("/") ? filename.substring(1) : filename;
LOG.warning("Called with file: " + filename);
status.set(Status.STOP);
try {
if(!filename.startsWith("/")) filename = "/" + filename;
File fullfile = new File(pathBase.getAbsolutePath() + filename);
if(fullfile.exists()) {
NSURL fullurl = new NSURL(NSURLScheme.File, "", fullfile.getAbsolutePath());
LOG.log(Level.SEVERE, "Loading URL: " + fullurl);
// Create audio player object and initialize with URL to sound
player = new AVAudioPlayer(fullurl);
LOG.log(Level.SEVERE, "Player initialized: " + player);
status.set(Status.STOP);
} else {
LOG.log(Level.WARNING, String.format("Audiofile doesn't exist: %s (%s / %s)",
fullfile.getAbsolutePath(),
pathBase.getAbsolutePath(),
filename));
player = null;
status.set(Status.ERROR);
}
} catch(NSErrorException error) {
LOG.log(Level.SEVERE, "Audio Setup Failed: " + error.toString(), error);
status.set(Status.ERROR);
}
}
#Override
public void play() throws NativeServiceException {
if(player == null) return;
player.play();
status.set(Status.PLAY);
}
#Override
public void pause() throws NativeServiceException {
if(player == null) return;
player.pause();
status.set(Status.PAUSE);
}
#Override
public void resume() throws NativeServiceException {
if(player == null) return;
player.play();
status.set(Status.PLAY);
}
#Override
public void stop() throws NativeServiceException {
if(player == null) return;
player.stop();
player.setCurrentTime(0.0);
status.set(Status.STOP);
}
#Override
public ReadOnlyObjectProperty<Status> statusProperty() {
return status.getReadOnlyProperty();
}
#Override
public Status getStatus() {
return status.get();
}
}

still on playing audio files on my android app

i'm new to this android thing and im going to create a sample app in which i can play an audio file. so, i'll show you a part of the class i created:
public class BBOX {
public static final int FORWARD = 0x09;
public static final int BACKWARD = 0x06;
public static final int CLOCKWISE = 0x05;
public static final int COUNTERCLOCKWISE = 0x0a;
public static final int FIRE = 0x10;
static MediaPlayer audioControl;
public static BBOX send(int data){
Context context;
if(data == FORWARD){
audioControl = MediaPlayer.create(context, R.raw.forward_100hz);
audioControl.start();
}
else if(data == BACKWARD){
audioControl = MediaPlayer.create(context, R.raw.backward_200hz);
audioControl.start();
the error is on the forward_100hz and backward_200hz... which are my audio files..
what did i miss?
Not sure what else you're doing wrong, but at the very least, your context is null where you pass it to MediaPlayer.create.
If you're using this method statically, you'll need to pass the context in from your Activity when you call it.
Welcome to Stack, btw. Don't forget to mark answers that are helpful with up-votes.
Just prepare the media player before playing the audio.
try {
audioControl = MediaPlayer.create(context, R.raw.forward_100hz);
audioControl.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
audioControl.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer paramMediaPlayer) {
paramMediaPlayer.start();
}
});

Record Audio Using AudioRecord in android

From the below code I can create test.pcm file but I couldn't play it in mobile or pc.
I have also tired with test.mp3, test.wav and test.raw. I got toast that player doesn't support this type of file.
does any one has idea that how can i play file which is i have recorded using AudioRecord?
Using below code I get array of short from mic and write it into SdCard.
Here is the Code:
package com.anroid.AudioProcess;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
public class AudioProcess extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Record 20 seconds of audio.
Recorder recorderInstance = new Recorder();
Thread th = new Thread(recorderInstance);
recorderInstance.setFileName(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.pcm"));
th.start();
recorderInstance.setRecording(true);
synchronized (this) {
try {
this.wait(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
recorderInstance.setRecording(false);
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Recorder implements Runnable {
private int frequency;
private int channelConfiguration;
private volatile boolean isPaused;
private File fileName;
private volatile boolean isRecording;
private final Object mutex = new Object();
// Changing the sample resolution changes sample type. byte vs. short.
private static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
/**
*
*/
public Recorder() {
super();
this.setFrequency(11025);
this.setChannelConfiguration(AudioFormat.CHANNEL_CONFIGURATION_MONO);
this.setPaused(false);
}
public void run() {
// Wait until we're recording...
synchronized (mutex) {
while (!this.isRecording) {
try {
mutex.wait();
} catch (InterruptedException e) {
throw new IllegalStateException("Wait() interrupted!", e);
}
}
}
// Open output stream...
if (this.fileName == null) {
throw new IllegalStateException("fileName is null");
}
BufferedOutputStream bufferedStreamInstance = null;
if (fileName.exists()) {
fileName.delete();
}
try {
fileName.createNewFile();
} catch (IOException e) {
throw new IllegalStateException("Cannot create file: " + fileName.toString());
}
try {
bufferedStreamInstance = new BufferedOutputStream(
new FileOutputStream(this.fileName));
} catch (FileNotFoundException e) {
throw new IllegalStateException("Cannot Open File", e);
}
DataOutputStream dataOutputStreamInstance =
new DataOutputStream(bufferedStreamInstance);
// We're important...
android.os.Process
.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
// Allocate Recorder and Start Recording...
int bufferRead = 0;
int bufferSize = AudioRecord.getMinBufferSize(this.getFrequency(),
this.getChannelConfiguration(), this.getAudioEncoding());
AudioRecord recordInstance = new AudioRecord(
MediaRecorder.AudioSource.MIC, this.getFrequency(), this
.getChannelConfiguration(), this.getAudioEncoding(),
bufferSize);
short[] tempBuffer = new short[bufferSize];
recordInstance.startRecording();
while (this.isRecording) {
// Are we paused?
synchronized (mutex) {
if (this.isPaused) {
try {
mutex.wait(250);
} catch (InterruptedException e) {
throw new IllegalStateException("Wait() interrupted!",
e);
}
continue;
}
}
bufferRead = recordInstance.read(tempBuffer, 0, bufferSize);
if (bufferRead == AudioRecord.ERROR_INVALID_OPERATION) {
throw new IllegalStateException(
"read() returned AudioRecord.ERROR_INVALID_OPERATION");
} else if (bufferRead == AudioRecord.ERROR_BAD_VALUE) {
throw new IllegalStateException(
"read() returned AudioRecord.ERROR_BAD_VALUE");
} else if (bufferRead == AudioRecord.ERROR_INVALID_OPERATION) {
throw new IllegalStateException(
"read() returned AudioRecord.ERROR_INVALID_OPERATION");
}
try {
for (int idxBuffer = 0; idxBuffer < bufferRead; ++idxBuffer) {
dataOutputStreamInstance.writeShort(tempBuffer[idxBuffer]);
}
} catch (IOException e) {
throw new IllegalStateException(
"dataOutputStreamInstance.writeShort(curVal)");
}
}
// Close resources...
recordInstance.stop();
try {
bufferedStreamInstance.close();
} catch (IOException e) {
throw new IllegalStateException("Cannot close buffered writer.");
}
}
public void setFileName(File fileName) {
this.fileName = fileName;
}
public File getFileName() {
return fileName;
}
/**
* #param isRecording
* the isRecording to set
*/
public void setRecording(boolean isRecording) {
synchronized (mutex) {
this.isRecording = isRecording;
if (this.isRecording) {
mutex.notify();
}
}
}
/**
* #return the isRecording
*/
public boolean isRecording() {
synchronized (mutex) {
return isRecording;
}
}
/**
* #param frequency
* the frequency to set
*/
public void setFrequency(int frequency) {
this.frequency = frequency;
}
/**
* #return the frequency
*/
public int getFrequency() {
return frequency;
}
/**
* #param channelConfiguration
* the channelConfiguration to set
*/
public void setChannelConfiguration(int channelConfiguration) {
this.channelConfiguration = channelConfiguration;
}
/**
* #return the channelConfiguration
*/
public int getChannelConfiguration() {
return channelConfiguration;
}
/**
* #return the audioEncoding
*/
public int getAudioEncoding() {
return audioEncoding;
}
/**
* #param isPaused
* the isPaused to set
*/
public void setPaused(boolean isPaused) {
synchronized (mutex) {
this.isPaused = isPaused;
}
}
/**
* #return the isPaused
*/
public boolean isPaused() {
synchronized (mutex) {
return isPaused;
}
}
}
MediaRecorder is your need here. If you do not plan to fiddle around with raw audio data, use a MediaRecorder object to do the recording. Set the output format to THREE_GPP and it should work for you.
Changing the file extension does not change the file format, so putting .mp3, for example, does not automatically create an MP3 file. AudioRecord produces raw PCM data.
You will have to tell the media player to play a raw file, and what kind of data to expect (sample rate, encoding etc) just as you did when making the recording, since this information is not given by the file itself.
You can read instructions for doing this in Audacity here: http://delog.wordpress.com/2011/03/25/playing-raw-pcm-audio-using-audacity/
Think you should use another class then AudioRecord.
AudioRecord is raw digital impressions of what is on your soundport right now.
And what you have "borrowed" up there for an code, is just a series of numbers.
Try AudioManager instead, think thats more your style.

How to put media controller in streaming video?

I am using SurfaceView to play streaming video and Media Player for streaming video. Can any one tell me how can I place media controller in surfaceview?
Here's my code:
package com.menu.donationvideos;
import android.app.Activity;
import android.media.AudioManager;
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;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.Toast;
import android.widget.VideoView;
import com.menu.R;
public class VideoPlay extends Activity implements OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback
{
private static final String TAG = "MediaPlayerDemo";
private int mVideoWidth;
private int mVideoHeight;
SurfaceHolder holder;
VideoInfo videoInfo;
String pos,videoURL;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private String path;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.video_play);
Bundle bundle=new Bundle();
bundle=this.getIntent().getExtras();
pos=bundle.getString("position");
videoInfo=VideoList.m_video.get(Integer.parseInt(pos));
videoURL=videoInfo.getVideoFile();
try
{
mPreview = (SurfaceView)findViewById(R.id.mySurfaceView);
holder=mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void playVideo()
{
doCleanUp();
try
{
path = videoURL;
if (path == "")
{
Toast.makeText(VideoPlay.this,"URL Not found", Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent)
{
Log.d(TAG,"Buffering:"+percent);
}
public void onCompletion(MediaPlayer arg0)
{
Log.d(TAG, "onCompletion called");
finish();
}
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();
}
#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();
}
}
do {
numread = stream.read(buf);
if (numread <= 0)
break;
totalBytesRead += numread;
totalKbRead = totalBytesRead/1000;
Log.e(getClass().getName(),"Buffered byte: " +totalBytesRead+"");
if(totalBytesRead>=100000){
if(mediaPlayer!=null){
int dura = mediaPlayer.getDuration();
if(mediaPlayer.getDuration()>=90000){
isInterrupted =false;
stream.close();
out.close();
out.flush();
break;
}
}
}
This is my code but I realized that media player doesnt start until streaming in progress.
I would suggest you take a look at the source code of VideoView, which combines everything at first place (or use VideoView instead of MediaPlayer itself)
hey nirav this code try it for media streaming
package com.pocketjourney.media;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
* MediaPlayer does not yet support streaming from external URLs so this class provides a pseudo-streaming function
* by downloading the content incrementally & playing as soon as we get enough audio in our temporary storage.
*/
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96*10/8;//assume 96kbps*10secs/8bits per byte
private TextView textStreamed;
private ImageButton playButton;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;
private int totalKbRead = 0;
// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();
private MediaPlayer mediaPlayer;
private File downloadingMediaFile;
private boolean isInterrupted;
private Context context;
private int counter = 0;
public StreamingMediaPlayer(Context context,TextView textStreamed, ImageButton playButton, Button streamButton,ProgressBar progressBar)
{
this.context = context;
this.textStreamed = textStreamed;
this.playButton = playButton;
this.progressBar = progressBar;
}
/**
* Progressivly download the media to a temporary location and update the MediaPlayer as new content becomes available.
*/
public void startStreaming(final String mediaUrl, long mediaLengthInKb, long mediaLengthInSeconds) throws IOException {
this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;
Runnable r = new Runnable() {
public void run() {
try {
downloadAudioIncrement(mediaUrl);
} catch (IOException e) {
Log.e(getClass().getName(), "Unable to initialize the MediaPlayer for fileUrl=" + mediaUrl, e);
return;
}
}
};
new Thread(r).start();
}
/**
* Download the url stream to a temporary location and then call the setDataSource
* for that local file
*/
public void downloadAudioIncrement(String mediaUrl) throws IOException {
URLConnection cn = new URL(mediaUrl).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {
Log.e(getClass().getName(), "Unable to create InputStream for mediaUrl:" + mediaUrl);
}
downloadingMediaFile = new File(context.getCacheDir(),"downloadingMedia.dat");
// Just in case a prior deletion failed because our code crashed or something, we also delete any previously
// downloaded file to ensure we start fresh. If you use this code, always delete
// no longer used downloads else you'll quickly fill up your hard disk memory. Of course, you can also
// store any previously downloaded file in a separate data cache for instant replay if you wanted as well.
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead/1000;
testMediaBuffer();
fireDataLoadUpdate();
} while (validateNotInterrupted());
stream.close();
if (validateNotInterrupted()) {
fireDataFullyLoaded();
}
}
private boolean validateNotInterrupted() {
if (isInterrupted) {
if (mediaPlayer != null) {
mediaPlayer.pause();
//mediaPlayer.release();
}
return false;
} else {
return true;
}
}
/**
* Test whether we need to transfer buffered data to the MediaPlayer.
* Interacting with MediaPlayer on non-main UI thread can causes crashes to so perform this using a Handler.
*/
private void testMediaBuffer() {
Runnable updater = new Runnable() {
public void run() {
if (mediaPlayer == null) {
// Only create the MediaPlayer once we have the minimum buffered data
if ( totalKbRead >= INTIAL_KB_BUFFER) {
try {
startMediaPlayer();
} catch (Exception e) {
Log.e(getClass().getName(), "Error copying buffered conent.", e);
}
}
} else if ( mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() <= 1000 ){
// NOTE: The media player has stopped at the end so transfer any existing buffered data
// We test for < 1second of data because the media player can stop when there is still
// a few milliseconds of data left to play
transferBufferToMediaPlayer();
}
}
};
handler.post(updater);
}
private void startMediaPlayer() {
try {
File bufferedFile = new File(context.getCacheDir(),"playingMedia" + (counter++) + ".dat");
// We double buffer the data to avoid potential read/write errors that could happen if the
// download thread attempted to write at the same time the MediaPlayer was trying to read.
// For example, we can't guarantee that the MediaPlayer won't open a file for playing and leave it locked while
// the media is playing. This would permanently deadlock the file download. To avoid such a deadloack,
// we move the currently loaded data to a temporary buffer file that we start playing while the remaining
// data downloads.
moveFile(downloadingMediaFile,bufferedFile);
Log.e(getClass().getName(),"Buffered File path: " + bufferedFile.getAbsolutePath());
Log.e(getClass().getName(),"Buffered File length: " + bufferedFile.length()+"");
mediaPlayer = createMediaPlayer(bufferedFile);
// We have pre-loaded enough content and started the MediaPlayer so update the buttons & progress meters.
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
} catch (IOException e) {
Log.e(getClass().getName(), "Error initializing the MediaPlayer.", e);
return;
}
}
private MediaPlayer createMediaPlayer(File mediaFile)
throws IOException {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(
new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what +") with extra (" +extra +")" );
return false;
}
});
// It appears that for security/permission reasons, it is better to pass a FileDescriptor rather than a direct path to the File.
// Also I have seen errors such as "PVMFErrNotSupported" and "Prepare failed.: status=0x1" if a file path String is passed to
// setDataSource(). So unless otherwise noted, we use a FileDescriptor here.
FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
mPlayer.prepare();
return mPlayer;
}
/**
* Transfer buffered data to the MediaPlayer.
* NOTE: Interacting with a MediaPlayer on a non-main UI thread can cause thread-lock and crashes so
* this method should always be called using a Handler.
*/
private void transferBufferToMediaPlayer() {
try {
// First determine if we need to restart the player after transferring data...e.g. perhaps the user pressed pause
boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
// Copy the currently downloaded content to a new buffered File. Store the old File for deleting later.
File oldBufferedFile = new File(context.getCacheDir(),"playingMedia" + counter + ".dat");
File bufferedFile = new File(context.getCacheDir(),"playingMedia" + (counter++) + ".dat");
// This may be the last buffered File so ask that it be delete on exit. If it's already deleted, then this won't mean anything. If you want to
// keep and track fully downloaded files for later use, write caching code and please send me a copy.
bufferedFile.deleteOnExit();
moveFile(downloadingMediaFile,bufferedFile);
// Pause the current player now as we are about to create and start a new one. So far (Android v1.5),
// this always happens so quickly that the user never realized we've stopped the player and started a new one
mediaPlayer.pause();
// Create a new MediaPlayer rather than try to re-prepare the prior one.
mediaPlayer = createMediaPlayer(bufferedFile);
mediaPlayer.seekTo(curPosition);
// Restart if at end of prior buffered content or mediaPlayer was previously playing.
// NOTE: We test for < 1second of data because the media player can stop when there is still
// a few milliseconds of data left to play
boolean atEndOfFile = mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile){
mediaPlayer.start();
}
// Lastly delete the previously playing buffered File as it's no longer needed.
oldBufferedFile.delete();
}catch (Exception e) {
Log.e(getClass().getName(), "Error updating to newly loaded content.", e);
}
}
private void fireDataLoadUpdate() {
Runnable updater = new Runnable() {
public void run() {
textStreamed.setText((totalKbRead + " Kb read"));
float loadProgress = ((float)totalKbRead/(float)mediaLengthInKb);
progressBar.setSecondaryProgress((int)(loadProgress*100));
}
};
handler.post(updater);
}
private void fireDataFullyLoaded() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
// Delete the downloaded File as it's now been transferred to the currently playing buffer file.
downloadingMediaFile.delete();
textStreamed.setText(("Audio full loaded: " + totalKbRead + " Kb read"));
}
};
handler.post(updater);
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void startPlayProgressUpdater() {
float progress = (((float)mediaPlayer.getCurrentPosition()/1000)/mediaLengthInSeconds);
progressBar.setProgress((int)(progress*100));
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
public void interrupt() {
playButton.setEnabled(false);
isInterrupted = true;
validateNotInterrupted();
}
/**
* Move the file in oldLocation to newLocation.
*/
public void moveFile(File oldLocation, File newLocation)
throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(getClass().getName(),"Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
}

Categories

Resources