i want to play mp4 video (which is playable for android) using videoview but it can't play the video.
my video is in sdcard folder,
can someone help me,
here is my code:
final VideoView vd = new VideoView(AboutActivity.this);
vd.setLayoutParams(new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.MATCH_PARENT)); linevideo.addView(vd);
MediaController mediaController = new MediaController (this);
mediaController.setAnchorView (vd); vd.setMediaController (mediaController);
Uri video = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/media/vid.mp4");
vd.setVideoURI(video); vd.requestFocus (); vd.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp){
mp.setLooping(true);
vd.start ();
}
});
at first try to change
vd.setVideoURI(video);
to
vd.setVideoPath(video);
and check are you add below permission in manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I have seen that when declaring a videoView inside a layout; it sometimes doesn't show because is hidden behind some other component. To solve this you would have to add this line of code:
vd.setZOrderOnTop(true);
On other cases (although I'm not sure why this happens) it has worked for me to set the background of the videoView to transparent.
vd.setBackgroundColor(Color.TRANSPARENT);
You are on right track,
just use mp.start(); inside listener
vd.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp){
mp.setLooping(true);
**mp.start ();**
}
});
Related
I have a project where I added a MediaPlayer in a custom Array Adapter and I make it take the Resource ID of the audio file from the Array List the problem is that I want to release the media player after the audio completes but every time I try to add release in OnCompletion and try to press a view while the media player plays a sound the app crashes .. I searched online and found a code but it gives me an error and I can't find the actual reason for such a crash.
that's the code for the on Click Listener and the Media player:
final MediaPlayer mediaPlayer = MediaPlayer.create(getContext(), currentWord.getVoiceResourceID());
// Wait for user's input by his click on the list's item to play the sound.
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Storing the return value of getVoiceResourceID() into mVoice.
// I think this line can be ignored so we call the method inside the creation of the Media Player.
// Creating our media player and put our track on it.
mediaPlayer.selectTrack(currentWord.getVoiceResourceID());
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release();
}
});
}
};
I hope I could fix that problem.
I am playing live stream from this URL in android
So far, I have managed to play the video in videoView, the problem was the video stopped exactly after 23 seconds, so I have used videoview method setOnCompletionListener(...) in order to start the video again, however, this provide bad experience for the viewer, because it stop every 23 seconds and start again, also miss several frames.
So my question is " how to make videoView buffer next part of video while playing current buffered video.
here is my code
public class TvActivity extends Activity {
// Declare variables
ProgressDialog pDialog;
VideoView videoview;
// Insert your Video URL
String VideoURL = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the layout from video_main.xml
setContentView(R.layout.videoview_main);
// Find your VideoView in your video_main.xml layout
videoview = (VideoView) findViewById(R.id.VideoView);
// Execute StreamVideo AsyncTask
VideoURL = "http://ns3622101.ip-149-202-201.eu:8000/live/fr443500/75019pa/286.ts";
// Create a progressbar
pDialog = new ProgressDialog(TvActivity.this);
// Set progressbar title
pDialog.setTitle("Video Streaming ");
// Set progressbar message
pDialog.setMessage("buffering ...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
// Show progressbar
pDialog.show();
try {
// Start the MediaController
final MediaController mediacontroller = new MediaController(
TvActivity.this);
mediacontroller.setAnchorView(videoview);
// Get the URL from String VideoURL
final Uri video = Uri.parse(VideoURL);
videoview.setMediaController(mediacontroller);
videoview.setVideoURI(video);
videoview.requestFocus();
videoview.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
videoview.start();
}
});
videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
videoview.stopPlayback();
videoview.setVideoURI(video);
videoview.requestFocus();
videoview.start();
}
});
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
}
As you are playing video from Live Stream URL I suggest you to Stream video by using third party Player to stream video and for buffer the next part of video, I suggest you to use Android GirrafePlayer it's good Player get it from here
And as you are Streaming .ts file I don't think android videoview will stream this video file so try to stream this video file with .ts file streaming supported Player.
For Live streaming and also for off-line audio or video playing I suggest used ExoPlayer
Which is very good library for playing audio and video developed by Google.
Short Intro is given bellow:
"ExoPlayer is an application level media player for Android. It provides an alternative to Android’s MediaPlayer API for playing audio and video both locally and over the Internet. ExoPlayer supports features not currently supported by Android’s MediaPlayer API, including DASH and SmoothStreaming adaptive playbacks. Unlike the MediaPlayer API, ExoPlayer is easy to customize and extend, and can be updated through Play Store application updates."
for more info search ExoPlayer on Github.
I'm playing video using VideoView in portrait mode (not on full screen). When I change to landscape mode, the video not resume (like youtube). Any Suggestion? Here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Checks the orientation of the screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_box_office_detail);
final ProgressDialog ringProgressDialog = ProgressDialog.show(BoxOfficeDetailActivity.this, "Please wait ...", "Video now loading ...", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(15000);
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
videoView =(VideoView) findViewById(R.id.tvVideo);
tvTitle = (TextView) findViewById(R.id.tvTitle);
tvSynopsis = (TextView) findViewById(R.id.tvSynopsis);
tvCast = (TextView) findViewById(R.id.tvCast);
BoxOfficeMovie movie = (BoxOfficeMovie) getIntent().getSerializableExtra(BoxOfficeActivity.MOVIE_DETAIL_KEY);
loadMovie(movie);
}
public void loadMovie(BoxOfficeMovie movie) {
videoView.setVideoPath(movie.getVideo());
MediaController mediaController = new
MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.start();
videoView.requestFocus();
tvTitle.setText(movie.getTitle());
tvCast.setText(movie.getCastList() + " views");
tvSynopsis.setText(movie.getSynopsis());
}
}
Avoid activity destruction, by adding this for the activity in the manifest android:configChanges="orientation|uiMode|screenSize"
Well odds are that on Orientation change you will need to destroy your video view and then reinstate it after the orientation change and resume playback from where it was left off at.
A little side note, I have had nothing but problems working with VideoView and MediaPlayer in Android development. Especially getting those 2 things to work correctly across multiple devices. If I were you, I would look into the ExoPlayer library to support video playback. But I guess that depends on how big of a part of your app video playback will be. ExoPlayer takes a significant more amount of time to get setup and working correctly however it still isnt hard and the performance and stability improvement make it work it.
First,I built a small app using videoview to play hls video with mp4 format on Samsung galaxt S2.With SD quality, video was smooth.But with HD quality,video was lag. Then, I built a larger app to play hls video using same videoview or mediaplayer android. When i played video, video was lag with SD and HD quality.
In small app, I have a string array to store URLs. My app allows user to choose a URL and push a button to throw a activity to play video using videoview:
Code using videoview in the small app :
VideoView vd = (VideoView)findViewById(R.id.videoView1);
MediaController mc = new MediaController(this);
mc.setAnchorView(vd);
Uri uri = Uri.parse(URL_link);
vd.setMediaController(mc);
vd.setVideoURI(uri);
vd.start();
In larger app, I using listfragment to display all URls. User choose a URLs, then throw a activity to playvideo using videoview. Code in the activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_channel_detail);
TextView tv = (TextView) findViewById(R.id.tvVideoPlayer);
Bundle extras = getIntent().getExtras();
if (extras != null) {
channel_id = extras.getInt(ChannelDetailActivity.CHANNEL_ID);
}
tv.setText("Video is playing...");
}
#Override
protected void onStart() {
super.onStart();
getChannelInfo();
}
private void getChannelInfo( ) {
TimeTVApiCaller.getInstance().getChannel(channel_id, this,
new AjaxCallback<ChannelInfo>() {
#Override
public void callback(String url, ChannelInfo object,
AjaxStatus status) {
if (object != null) {
Urlvideo = object.getChannelUrls().get(0).getPath();
getURLfull(Urlvideo);
}
}
});
}
//get a full URL
protected void getURLfull(String url)
{
TimeTVApiCaller.getInstance().getChannelStream(url, this, new AjaxCallback<String>()
{
#Override
public void callback(String url, String object,
AjaxStatus status) {
String Urlfull = object.replace("\"", "");
Urltoken = Urlfull;
//Using the same videoview
VideoView vd = (VideoView) findViewById(R.id.videoView1);
MediaController mc = new MediaController(ChannelDetailActivity.this);
mc.setAnchorView(vd);
Uri uri = Uri.parse(Urltoken);
vd.setMediaController(mc);
vd.setVideoURI(uri);
vd.start();
//vd.requestFocus();
}
});
}
}
I have two questions :
Why videoview or mediaplayer play hls video is lag?
How to custom videoview or mediaplayer to play hls video smoothly?
Each segment in HLS aka HTTP Live Streaming is typically 10 seconds.
The player measures the time it takes to get each segment, if it took too long it will try to pick a bandwidth where it can get a segment or more before it plays it. And the most common error is buffering delays.
You should look in the log file to see what the player is doing when playing content.
If the above is not helpful, this might help.
I assume HD quality is at least 720p and more than 1.5 mbps bit stream with h.264/avc encoding. My best guess is that S2 Hardware doesn't support it.
I have code to play an .ogg audio file, that I downloaded from the internet. I have no errors, so I can run it, but then the app crashes:
package play.my.sound;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
public class PlaySound2Activity extends Activity {
private SoundPool soundPool;
private int soundID;
boolean loaded = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = findViewById(R.id.textView1);
view.setOnClickListener((OnClickListener) this);
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = soundPool.load("sound1.ogg", 1);
}
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService (AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}
return false;
}
}
I think I have two problems:
I put this in the main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="Click on the screen to start playing"
android:id="#+id/textView1" android:layout_width="fill_parent"
android:layout_height="fill_parent"></TextView>
</LinearLayout>
And I don't know if it's correct.
I put the file sound1.ogg in the workspace->SoundPlay2 folder because in the res folder I had problems, and also, I tried to put it in the two res folders that exist.
This is from my console:
[2012-01-04 19:38:16 - PlaySound2] Failed to install PlaySound2.apk on device 'emulator-5554': timeout
[2012-01-04 19:38:16 - PlaySound2] Launch canceled!
[2012-01-04 19:47:33 - PlaySound2] Error in an XML file: aborting build.
[2012-01-04 19:52:34 - PlaySound2] res\layout\main.xml:0: error: Resource entry main is already defined.
[2012-01-04 19:52:34 - PlaySound2] res\layout\main.out.xml:0: Originally defined here.
[2012-01-04 19:52:34 - PlaySound2] C:\Users\Natalia\workspace\PlaySound2\res\layout\main.out.xml:1: error: Error parsing XML: no element found
I took this example from "Android Sounds - Tutorial".
I want to play an audio file, more specifically, a .wav file.
I dont' know where I can find some information about the files that are permitted in the MediaPlayer class and their characteristic (durantion, sample rate...) Could you tell me where I can find this??
Create raw folder in the res folder and add your file to it. Then play the file using
soundID = soundPool.load(R.raw.sound1, 1);
And also see this post for your main.xml problem.
I've never seen the Class SoundPool before, however I would recommend using a MediaPlayer Class:
mMediaPlayer = new MediaPlayer(this, R.raw.yourfile);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
mMediaPlayer.start();
Make sure you put the file into the folder PROJECT/res/raw/ (or create it if it does not exist)
Also there is something wrong with your main.xml. Can you please post it?
Example for playing some kind of buzzer. In the res folder under raw folder I have a buzzer.wav
Method to play this buzzer:
/**
* Method to play an alarm sound to signal half time or full time.
*/
private void playAlarm() {
MediaPlayer mp = MediaPlayer.create(this,
R.raw.buzzer);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
first you need to save sound1.ogg file in src\main\res\raw directory
instated of direct passing "sound1.ogg" file , pass file this way R.raw.sound1
soundID = soundPool.load(R.raw.sound1, 1);
To be honest I would always prefer Mediaplayer over any other api.After downloading file save it to external storage or raw folder and play it using the given methods or you can directly play it from internet.Caution: Be careful of buffering.
To play audio directly from internet add these code. Note: Api version >= 21 and make sure to add internet permission in manifest
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)//This method requires android version more than 20
public void playSoundFrom_internet(String url) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
}catch(IOException E){
E.printStackTrace();
}
}
To play audio from res folder:
public void playSoundFrom_raw(#RawRes int rawId, Context context){
MediaPlayer mediaPlayer = MediaPlayer.create(context,rawId);
mediaPlayer.start();
}
To play audio from file. Note: Make sure to add storage permission
public void playSoundFrom_file(String filePath){
try {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
That's not how OnClickListener be implemented, that's an Interface to implement in the class not force casted to. You did that as a quick fix but blew back onto you since AudioManager got running first so you thought that is at fault.