Seamless video Loop with VideoView - android

I have the following code to take a video as a raw resource, start the video and loop it but I need the video to loop seamlessly as of now when it comes to an end of the clip and starts the clip again the transition between causes a flicker for a split second, which I really can't have for my app.
public class Example extends Activity {
VideoView vv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vv = (VideoView)findViewById(R.id.VideoView01);
//Video Loop
vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
vv.start(); //need to make transition seamless.
}
});
Uri uri = Uri.parse("android.resource://com.example/"
+ R.raw.video);
vv.setVideoURI(uri);
vv.requestFocus();
vv.start();
}
}
The clip is only 22 seconds long but was created to be seamless so it is possible to work without the delay.

Try this it will work 100%
VideoView videoView;<---write this in outside of method or else declare it as final variable.
videoView.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});

In Kotlin simply use
videoView.setOnPreparedListener { it.isLooping = true }

Not sure if this helps years later, but I used
vv.start();
vv.setOnCompletionListener ( new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
vv.start();
}
});
and it has a seamless loop

The pause is for the underlying MediaPlayer to refresh its buffers. How long that will take will depend on a number of factors, many of which are outside your control (e.g., speed of CPU, speed of on-board flash storage).
One you can control is to get your video out of the resource and into the filesystem. Resources are stored in the APK, which is a ZIP file, so extracting the video this way probably takes extra time.
You may need to switch away from VideoView and use a SurfaceView with two MediaPlayers, alternating between them -- one is playing while the next is preparing, so when the playing one ends you can switch to the new player. I have not tried this, and so I do not know what the ramifications might be. However, I know that this technique is frequently used for audio playback to transition from one clip to another.

Little late, but any reason that you can't use the following?
MediaPlayer.setLooping(true);

If you are using Kotlin
videoView.setOnPreparedListener(object : MediaPlayer.OnPreparedListener {
override fun onPrepared(mp: MediaPlayer?) {
//Start Playback
videoView.start()
//Loop Video
mp!!.isLooping = true;
Log.i(TAG, "Video Started");
}
});
Using Arrow Expression short form
videoView.setOnPreparedListener { mp ->
//Start Playback
videoView.start()
//Loop Video
mp!!.isLooping = true;
Log.i(TAG, "Video Started");
};

Answer to this is to remove the audio from the video and convert that to a .ogg file which can be looped seamlessly and then use the video without audio to loop round and this works.

Here is answer friends, you must use vv.resume in setOnCompletionListener class
[https://stackoverflow.com/a/27606389/3414469][1]

Related

VideoView seekTo 0 instead of specific position

I'm trying to start video from specific position but VideoView has strange behave. When I run code like that
videoView.seekTo(2000)
int current = videoView.getCurrentPosition()
Log.e("Current Time", String.valueOf(current))
Log gives me value 0. It should give 2000 because this is current position. Even If I implement onPreparedListener it doesn't worked (but in different way). It display proper value (2000) but video still is not seek.
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp)
{
videoView.getDuration();
videoView.seekTo(2000);
Log.e("Current: ", String.valueOf(videoView.getCurrentPosition()));
}
});
How to fight this ? If I will build MediaPlayer + SurfaceView it will helps or will behave same as VideoView ?
Actually, the thing is,VideoView.seekTo() is a wrapper around MediaPlayer.seekTo(). This function returns almost immediately even though the actual seeking is still being performed. Therefore you want to wait for seeking to complete via MediaPlayer.OnSeekCompleteListener.
However, the standard VideoView does not support OnSeekCompleteListener.
But you can copy and locally customize the VideoView class to add this support yourself.
Or, You could try this
mVideoView.setOnPreparedListener(new MediaPlayer .OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setOnSeekCompleteListener(new OnSeekCompleteListener() {
#Override
public void onSeekComplete(MediaPlayer mp) {
Log.e("Current: ", String.valueOf(videoView.getCurrentPosition()));
}
});
}
});
videoView.seekTo(2000); //or wherever the call is to be made
Hope this should help.

VideoView Looping displays black screen after the first loop

I'm using VideoView to loop a small video, all works fine on the emulators, but when I deploy that to TV, after the first loop video turns black, but sound keeps going. This is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
VideoView videoview = (VideoView) findViewById(R.id.videoview1);
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.video);
videoview.setVideoURI(uri);
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
videoview.start();
}
});
}
The Emulator is using Android 6.0, the TV is Sony Bravia with Android 6.0.1.
I tested using SurfaceView, instead of VideoView - the same thing happens.
Any idea how to get rid of that black screen?
PS: There is a workaround that works - make OnCompletionListener and do videoview.start() there - this way it loops, but there's an ugly gap between the loops.
Just use this mVideoView.setZOrderOnTop(true); It will not show the black screen as the view appears.
Try to set your VideoView using handler like this.
videoview.setBackgroundColor(Color.WHITE); //color what you want as background
videoview.postDelayed(new Runnable() {
#Override
public void run() {
videoview.setVideoURI(videoUri);
}
}, 100);
videoview.postDelayed(new Runnable() {
#Override
public void run() {
vv.setBackgroundColor(Color.TRANSPARENT);
}
}, 300);
videoview.requestFocus();
videoview.start();
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { #Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
I have looked into the source code of VideoView and the first thing that I would like to point out is that inside the setVideoURI() method the MediaPlayer object will be created, and the OnPreparedListener will be set.
Your mistake is that you set the OnPreparedListener after the MediaPlayer may already have prepared the video, thus never call the onPrepared in the listener you have set after that, which means the setLooping(true) was maybe never set on the MediaPlayer.
TL;DR:
Put videoview.setVideoURI(uri); after videoview.setOnPreparedListener().
videoview.start() should be after setVideoURI(). On finish it should start again without additional input because this time mp.setLooping(true); was correctly set and will be executed. No videoview.start() is necessary after the initial one.
I actually ended up using ExoPlayer instead of the default one.
It's a bit harder to set up, but this problem didn't show up there.

multiple videos play one after the another

can anyone teach me how to make videos play one after the other
I need the full code
I have 4 videos
Video1, Video2, Video3, Video4
I want Video1 to play first then followed Video2, then followed by Video3, then followed by Video4
String path="android.resource://" + getPackageName() +"/" + R.raw.Video1;
videoView1.setVideoURI(Uri.parse(path));
videoView1.start();
Short & Simple
Let's say you have four videos in array list
ArrayList<String> urlList = new ArrayList<>();
Create one counter variable to manage current video playing.
int video_counter = 0;
Now following code make your work easy to play dynamic range of video to play in loop (like one after another).
VideoView vv_video = findViewById(R.id.vv_video);
vv_video.setVideoURI(Uri.parse(urlList.get(counter_video_loop)));
vv_video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
vv_video.start();
}
});
vv_video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if ((video_counter + 1) <= urlList.size()) {
video_counter++;
vv_video.setVideoURI(Uri.parse(urlList.get(video_counter + 1)));
vv_video.start();
}
}
});
Assume you have a Videoview, you could for example put the paths to the videos into an array, and detect the end of playback like this:
videoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//start next video here
//for example, set video path to next array item
}
});
Maybe you should create a new VideoView to play next video at OnCompletionListener, and remove the old VideoView ,add the new VideoView.
It works for me.
use exoPlayer for concatenate multi video

How to create and play a sound or audio queue in Android

I have many short audio fragments which should be played sequentially with minimum latency.
How can I queue these sounds efficiently?
There are two ways I can see this working: using a MediaPlayer or a SoundPool
MediaPlayer
You can use MediaPlayer.OnCompletionListener combined with a list of files to simply listen for completion and play the next one. By and large this works quite well and I have used it to play sequences of very short clips (< 1s) without problems.
SoundPool
Another way is to use the SoundPool class combined with a handler to simply queue up play events in advance. This assumes you know the length of each clip but depending on the format you should be able to find this out.
Which solution you choose depends on a number of factors: how many files, how short they are, what format they are in, where you are getting them from, how fixed or variable the list is, etc.
Personally I would go with MediaPlayer as this is easier to implement and would probably fit your needs.
One way is to concatenate them into a single audio file, then create a MediaPlayer for it and set an OnSeekCompleteListener. Seek to each segment in tern in whichever order you like and then play them in onSeekComplete(). It's timing not exact and MediaPlayer is touchy to use so it may not be the best choice for you but it's good enough for my purposes.
Here's my code:
private MediaPlayer MP = new MediaPlayer();
#Override
public void onCreate(Bundle savedInstanceState) {
//...
FileDescriptor fd = getResources().openRawResourceFd(R.raw.pronounciations).getFileDescriptor();
try {
setVolumeControlStream(AudioManager.STREAM_MUSIC); // Lets the user control the volume.
MP.setDataSource(fd);
MP.setLooping(false);
MP.prepare();
MP.start(); // HACK! Some playing seems required before seeking will work.
Thread.sleep(60); // Really need something like MediaPlayer.bufferFully().
MP.pause();
MP.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
MP.setOnSeekCompleteListener(new OnSeekCompleteListener() {
public void onSeekComplete(MediaPlayer mp) {
// The clip is queued up and read to play.
// I needed to do this in a background thread for UI purposes.
// You may not need to.
new Thread() {
#Override
public void run() {
MP.start();
try {
Thread.sleep(soundRanges[curWordID][1]);
} catch(InterruptedException e) {}
MP.pause();
}
}.start();
}
});
} catch(Throwable t) {}
}
private void playCurrentWord() {
if(soundRanges != null && !MP.isPlaying() && !silentMode) {
try {
MP.seekTo(soundRanges[curWordID][0]);
}
catch(Throwable t) {}
}
}
You would likely need to concatenate your clips using an external sound editing tool. I used Audacity to find and edit the clip beginnings and lengths that I saved in a file.
soundRanges[curWordID][0] is the offset in the sound file of the beginning of a clip and soundRanges[curWordID][1] is its length.

Mediaplayer error (-19,0) after repeated plays

I have a game in which a sound plays when a level is completed. Everything works fine to start with but after repeating a level 10 or 20 times the logcat suddenly reports:
"MediaPlayer error (-19,0)" and/or "MediaPlayer start called in state 0" and the sounds are no longer made.
I originally had the all sounds in mp3 format but, after reading that ogg may be more reliable, I converted them all to ogg, but the errors appeared just the same.
Any idea how I can fix this problem?
I was getting the same problem, I solved it by adding the following code to release the player:
mp1 = MediaPlayer.create(sound.this, R.raw.pan1);
mp1.start();
mp1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
I think you are not releasing the mediaplayers you are using to play the sound..
You need to release() the media players otherwise the resources are not released , and you soon get out of memory (since you allocate them again next time). so,I think you can play twice or even thrice... but not many times without releasing the resources
MediaPlayer is not a good option when you are playing small sound effects as the user can click on multiple buttons very soon and you will have to create a MP object for all of them which doesnt happen synchronously. That is why you are not hearing sounds for every click. Go for the SoundPool Class which allows you to keep smaller sounds loaded in memory and you can play them any time you want without any lag which you would feel in a mediaplayer. http://developer.android.com/reference/android/media/SoundPool.html Here is a nice tutorial : http://www.anddev.org/using_soundpool_instead_of_mediaplayer-t3115.html
I solved both the errors (-19,0) and (-38,0) , by creating a new object of MediaPlayer every time before playing and releasing it after that.
Before :
void play(int resourceID) {
if (getActivity() != null) {
//Using the same object - Problem persists
player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
After:
void play(int resourceID) {
if (getActivity() != null) {
//Problem Solved
//Creating new MediaPlayer object every time and releasing it after completion
final MediaPlayer player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
This is a very old question, But this came up first in my search results So other people with the same issue will probably come upon this page eventually.
Unlike what some others have said, you can in fact use MediaPlayer for small sounds without using a lot of memory. I'll put in a little modified snippit from my soundboard app to show you what I'm getting at.
private MediaPlayer mp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
mp = new MediaPlayer();
}
private void playSound(int soundID){
mp.reset();
AssetFileDescriptor sound = getResources().openRawResourceFd(soundID);
try {
mp.setDataSource(sound.getFileDescriptor(),sound.getStartOffset(),sound.getLength());
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
with the way I set it up, you create on MediaPlayer object that you reuse everytime you play a sound so that you don't use up too much space.
You call .reset() instead of .release() because .release() is only used if you are disposing of an object, however you want to keep your MediaPlayer Object.
You use an assetfiledescriptor to set a new soundfile for your mediaplayer to play instead of setting a new object to your mediaplayer address because that way you are creating new objects within the method that aren't being handled properly and you will eventually run into the same error as you described.
This is only one of many ways to use MediaPlayer but I personally think it is the most efficient if you are only using it for small sound applications. The only issue with it is that it is relatively restrictive in what you can accomplish, but that shouldn't be much of an issue if you are indeed using it for small sound applications.
i try delete emulator and new create emulator for remove error of (-19,0) media player.

Categories

Resources