I used the tutorial here (https://examples.javacodegeeks.com/android/android-videoview-example/) to build a videoview activity in my app though it keeps crashing when it's opened. I can't figure it out to save my life. I've checked the other posts on here and none of the suggestions have
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.MediaController;
import android.widget.VideoView;
public class DemoActivity extends AppCompatActivity {
private VideoView myVideoView;
private int position = 0;
private ProgressDialog progressDialog;
private MediaController mediaControls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quote);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// set the main layout of the activity
setContentView(R.layout.activity_main);
//set the media controller buttons
if (mediaControls == null) {
mediaControls = new MediaController(DemoActivity.this);
}
//initialize the VideoView
myVideoView = (VideoView) findViewById(R.id.video_view);
// create a progress bar while the video file is loading
progressDialog = new ProgressDialog(DemoActivity.this);
// set a title for the progress bar
progressDialog.setTitle("JavaCodeGeeks Android Video View Example");
// set a message for the progress bar
progressDialog.setMessage("Loading...");
//set the progress bar not cancelable on users' touch
progressDialog.setCancelable(false);
// show the progress bar
progressDialog.show();
try {
//set the media controller in the VideoView
myVideoView.setMediaController(mediaControls);
//set the uri of the video to be played
myVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.demo));
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
myVideoView.requestFocus();
//we also set an setOnPreparedListener in order to know when the video file is ready for playback
myVideoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
// close the progress bar and play the video
progressDialog.dismiss();
//if we have a position on savedInstanceState, the video playback should start from here
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
} else {
//if we come from a resumed activity, video playback will be paused
myVideoView.pause();
}
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//we use onSaveInstanceState in order to store the video playback position for orientation change
savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());
myVideoView.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//we use onRestoreInstanceState in order to play the video playback from the stored position
position = savedInstanceState.getInt("Position");
myVideoView.seekTo(position);
}
}
In your code have two setContentView() for two layout. That is reason of your error. You need merge two layout and sure that VideoView available on that view.
Related
I adding VideoView in fragment but only I get black background nothing more I tried with two codes but both doesn't work can you help me?
PS I don't need play, stop button and anything other just to show the video Here is the code that I add will be good if I can mute the audio of the video and replay
Code 1
package com.Hristijan.Aleksandar.GymAssistant.Exercises;
import android.media.session.MediaController;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.VideoView;
import java.net.URL;
/**
* A simple {#link Fragment} subclass.
*/
public class BenchFragment extends Fragment {
private VideoView MyVideoView;
public BenchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bench, container, false);
MyVideoView = (VideoView)rootView.findViewById(R.id.video_view);
Uri uri= Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.bench);
MyVideoView.setVideoURI(uri);
MyVideoView.start();
return inflater.inflate(R.layout.fragment_bench, container, false);
}
}
Code2
package com.hristijan.aleksandar.gymworkout.myapplication;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.VideoView;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private VideoView MyVideoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyVideoView = findViewById(R.id.videoViewId);
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bench);
MyVideoView.setVideoURI(uri);
MyVideoView.start();
}
}
Layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
tools:context="com.Hristijan.Aleksandar.GymAssistant.Exercises.BenchFragment">
<VideoView
android:id="#+id/video_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Try this to play,replay and identify the error
private void startVideo() {
String path = "android.resource://" + getPackageName() + "/" + R.raw.crop;
// Log.e(TAG,Uri.parse(path) + " ");
video_view.setVideoURI(Uri.parse(path));
video_view.start();
video_view.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int i, int i1) {
Log.e(TAG,String.format("Error: What: %d, Extra: %d",i,i1));
return false;
}
});
video_view.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.start();
}
});
}
If the video doesn't play it should log error in LogCat. You can identify what kind of error using this doc
About Muting the Audio
You can refer to this Question basically you just need to get the media player object when the content is ready then you can mute the audio by setting m.setVolume(0f, 0f);
I am sure that Code 1 and Code 2 can work
First, make sure your video format is Supported Media Formats
Then, make sure your video file bench stored in ...app\src\main\res\raw (And your file name should be bench not bench.xxx)
On the other hand, in Code 2 something is wrong:
MyVideoView = findViewById(R.id.videoViewId);
should be
MyVideoView = findViewById(R.id.video_view);
in order to find a VideoView by correct Id
Try putting videoView.start() inside videoView.setOnPreparedListener() as:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mediaPlayer){
videoView.start();
}
});
I'm making music player app for Android and i have problem with keeping music playing while i change orientation of phone.
package nori.beta.musicplayer;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import nori.beta.musicplayer.Class.BlurBuilder;
import nori.beta.musicplayer.Fragment.Playlist;
import nori.beta.musicplayer.Fragment.Utilities;
public class MainActivity extends Activity {
private ImageView bg; // blured backgroud of size of screen
private ImageView cover; // small image in center of activity that plays song
private BlurBuilder blured; // class to blur image for background
private SeekBar
progressBar; // Creating seekbar that show progress of song and allow us scroll and rewind song
private ImageButton
play_pause_stopButton; //on click do 1.play/2.paues/3.stop for all change icon
private MediaPlayer player; // Player that play music
private Handler mHandler = new Handler(); //Handler that help with refreshing progressBar
private Utilities utils; //Change seconds into min + sec
ArrayList<File> mySongs; // list of music file
ArrayList<Song> songsInfo; //list of music file with extract information about them
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// init all GUI staff
initGUI();
setButtons();
}
#Override
protected void onResume() {
super.onResume();
// init Database and rest of gui staff that need database
// Here have u data of all file and chosen song and can u make to play song
}
private void initGUI() {
// Image Part
bg = (ImageView) findViewById(R.id.main_background);
cover = (ImageView) findViewById(R.id.cover_image);
blured = new BlurBuilder();
//Buttons
play_pause_stopButton = (ImageButton) findViewById(R.id.play_pause_stop_button);
progressBar = (SeekBar) findViewById(R.id.progressBar);
player = new MediaPlayer();
utils = new Utilities();
mySongs = findSongs(Environment.getExternalStorageDirectory());
songsInfo = new ArrayList<Song>();
for (File f : mySongs) {
songsInfo.add(new Song(f));
}
//progressBar.setOnSeekBarChangeListener(this);
}
private ArrayList<File> findSongs(File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles();
/**
* findSongs Search for music file in memory
*
* for each file in memory
* 1.if is that file a folder , then take all file then give it in method findSongs
* and with requrency
* 2.Else if that file end with .mp3 or .wav ,then add to list
*/
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
//Log.e("findsongs","Folder");
} else {
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) {
al.add(singleFile);
Log.e("FileInfo.GetSong", singleFile.getName().toString());
}
}
}
return al;
}
private void setButtons() {
play_pause_stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //Play/Pause song button clicked
playSong(0);
}
});
progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { //Using progress bar to scrolling song
#Override
public void onStopTrackingTouch(SeekBar progressBar) {
}
#Override
public void onStartTrackingTouch(SeekBar progressBar) {
}
#Override
public void onProgressChanged(SeekBar progressBar, int progress, boolean fromUser) { //When user move progress bar song go to moment that user choosed
if (player != null && fromUser) {
player.seekTo(progress * 1000);
}
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) { //When song ended playing
playSong(0);
}
});
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100); //Updating progressBar every 100ms
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() { //Updating time of song and progressbar
long totalDuration = player.getDuration();
long currentDuration = player.getCurrentPosition();
// Updating progress bar
int mCurrentPosition = player.getCurrentPosition() / 1000;
progressBar.setProgress(mCurrentPosition);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
// set it in all changes of the privius songs <#-- Krzysiek -->
private void setBackground(int i) {
//setting the back image and cover image to the chosen song
if (songsInfo.get(i).getBackground() != null) {
bg.setImageBitmap(blured.blur(this, songsInfo.get(i).getBackground()));
cover.setImageBitmap(songsInfo.get(i).getBackground());
Log.i("FileInfo.SetCover", "Set cover of " + songsInfo.get(i).getName());
}
}
public void playSong(int index) {
try {
player.reset();
player.setDataSource(songsInfo.get(index).getPath()); //Getting song with proper index from list
player.prepare();
player.start(); //Playing prepared song
// Displaying Song title
String songTitle = songsInfo.get(index).getTitle();
String songArtist = songsInfo.get(index).getArtist();
setBackground(index);
// Changing Button Image to pause image
play_pause_stopButton.setImageResource(R.drawable.pause);
// set Progress bar values
progressBar.setProgress(0);
progressBar.setMax(player.getDuration() / 1000);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I tried with
android:configChanges="orientation|screenSize"
in manifest and it work but only for 1st change from vertical to horizontal orientation. When i change again from horizontal to vertical, same song start from beggining while old is still playing so i have 2 songs played at same moment. Can anyone help me with it?
keep the config changes and add an override to the onconfig...
#Override
public void onConfigurationChanged(Configuration newConfig) {
}
when the orientation changes the oncreate is called by default , you need to override it like this example or maybe use a singleton as a mediaplayer so it won't create two of them
It was just stupid but i just make player static. It helped and now it dont create additional instances
When you orientate your device, it redraw your layouts and that's why activity restarts (calls onConCreate()). You can save your instance with overriding this method:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
and restore instance with overriding this method:
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
I created source in github about this topic, saving instances and restoring. Maybe it'll help you in some circumstances. Orientation Mode
I create a simple project with one layout that contains two buttons, and this is my code:
package com.example.tessound;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener
{
MediaPlayer player;
Button play,mute;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id.button1);
play.setOnClickListener(this);
mute = (Button)findViewById(R.id.button2);
mute.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View view)
{
if(view.getId()==R.id.button1)
{
playSound(1);
}
else if(view.getId()==R.id.button2)
{
playSound(2);
}
}
public void playSound(int arg)
{
if (arg == 1)
{
player = MediaPlayer.create(this, R.raw.atur);
}
else if (arg == 2)
{
player = MediaPlayer.create(this, R.raw.back);
}
if(player != null)
{
player.setLooping(false);
player.start();
}
try
{
if(player != null)
{
if (player.isPlaying())
{
player.stop();
player.release();
}
}
}
catch(Exception e)
{
}
}
}
When I tried to click the button the sound doesn't play.
Following the logic for your playSound method with an argument value of 1:
1) arg == 1 so:
player = MediaPlayer.create(this, R.raw.atur);
2) player has been set so is not null, hence:
player.setLooping(false);
player.start();
3) Then it's your try block. player is not null and is playing, hence:
player.stop();
player.release();
So I think you are starting the playback and then immediately stopping it. I imagine you should only execute the try/catch code if the method does not receive a valid argument, i.e. it should be an 'else' of the preceding 'if' statement.
EDIT:
Looking at this again, I think the try/catch code should go at the top of the method. It will then stop the player and release it (if it is in use) before trying to start playing a new sound. Logically that makes sense.
Use Log to trace the control and find the error !
Log.e("AnyTAG","Description of the Log");
your code seems fine!
I have bought Foscam Security Camera and I am able to see the JPEG streaming on my MacBook.
But when I open the same link in my phone browser using chrome then it starts downloading something not sure what and in notification menu shows unsuccessful download.
Plus if I open the same link on my Android Firefox browser then I am able to see the video.
I have to create an android application to show the streaming of the video just as it is viewable on laptop browser.
The following is the code I am using:
package org.securitycamera;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.VideoView;
public class SecuritycameraActivity extends Activity {
WebView webView;
FrameLayout frameLayout;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflator = getLayoutInflater();
View inflatedView = inflator.inflate(R.layout.main, null);
if (!(inflatedView instanceof FrameLayout))
{
throw new RuntimeException("inflated view not FrameLayout");
}
else
{
frameLayout = (FrameLayout)inflatedView;
}
setContentView(frameLayout);
webView = (WebView) findViewById(R.id.wv);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(android.webkit.WebSettings.PluginState.ON);
webView.setWebChromeClient(new MyWebChromeClient());
try
{
// webView.loadUrl("http://192.168.1.6/videostream.cgi?user=admin&pwd=");
webView.loadUrl("http://broken-links.com/tests/video/");
}
catch(Exception e)
{
throw new RuntimeException();
}
}
private class MyWebChromeClient extends WebChromeClient implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener {
VideoView videoView;
WebChromeClient.CustomViewCallback customViewCallback;
public void onProgressChanged(WebView view, int newProgress)
{
if (newProgress == 100)
{
view.loadUrl("javascript:playVideo()");
}
}
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
if (view instanceof FrameLayout){
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView){
VideoView video = (VideoView) frame.getFocusedChild();
frame.removeView(video);
setContentView(video);
video.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Log.i(DVNGActivity.TAG, "LoadData_QRURL --> onCompletion...");
mp.stop();
setContentView(R.layout.main);
}
});
video.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// Log.i(DVNGActivity.TAG, "LoadData_QRURL --> onError");
return false;
}
});
video.start();
}
}
}
public void onPrepared(MediaPlayer mp)
{
}
public void onCompletion(MediaPlayer mp)
{
// this is needed to release the MediaPlayer and its resources so it can
// be used again later
videoView.stopPlayback();
// now remove the video and tell the callback to hide the custom view
frameLayout.removeView(videoView);
customViewCallback.onCustomViewHidden();
finish();
}
public boolean onError(MediaPlayer mp, int what, int extra)
{
return false; // we did not handle the error - onCompletion will be called
}
}
}
I followed this How to Play HTML5 video and YouTube Video within Android WebView?, and if instead of playing the video in example I play the video of my security camera i.e.
webView.loadUrl("http://192.168.1.6/videostream.cgi?user=admin&pwd=");
I get a white screen.
this sample https://gist.github.com/3718414 has an Android webview wrapper and HTML5 video - it's not as simple as just referencing the URL (if you want the video in the webView) but it's not difficult on ICS and above (ensuring you have hardware acceleration enabled seems to be pretty key)
I need to increase voice, recorder from microphone on Android device.
I try to read buffer from AudioRecord and then write it to AudioTrack... It works, but with delay, because min buffer size, returned bu method AudioRecord.getMinBufferSize with frequency like 44100 is 4480 bytes.
Any ideas?
Thanks.
I have this code
AudioRecord and AudioTrack latency
But it happens to that there is a 20ms delay, and I need to solve it,
The code above seems that plays something but there is no mic input, does it work?
Thanks!
I noticed there is no threading code. I would recommend trying to thread the recording and playback aspects and see if that better avoids the latency. Fill the buffer in from the mic one thread, and read it out to the speaker in the other. Avoid buffer overflows and underruns by handling those situations with some action (e.g. clearing the buffer for overflows). In theory, one should keep up with the other.
package org.example.audio;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AudioDemo extends Activity implements OnClickListener {
private static final String TAG = "AudioDemo";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
MediaPlayer player;
Button playerButton;
public void onClick(View v) {
Log.d(TAG, "onClick: " + v);
if (v.getId() == R.id.play) {
playPause();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//player = MediaPlayer.create(this, R.raw.robotrock);
player.setLooping(false); // Set looping
// Get the button from the view
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop_label);
playerButton.setOnClickListener(this);
// Begin playing selected media
demoPlay();
// Release media instance to system
player.release();
}
#Override
public void onPause() {
super.onPause();
player.pause();
}
// Initiate media player pause
private void demoPause(){
player.pause();
playerButton.setText(R.string.play_label);
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, notPlaying);
}
// Initiate playing the media player
private void demoPlay(){
player.start();
playerButton.setText(R.string.stop_label);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, isPlaying);
}
// Toggle between the play and pause
private void playPause() {
if(player.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
}