How to play live streaming in android application? - java

I want to make application for cricket live streaming.
I want to know following things :
From where I can found the links to play cricket streaming ?
Which type of links are these ?
Is there any player to play this type of videos ?
Currently, I have implemented web page but I am looking for other alternative.
Below is my code :
link1 = (RelativeLayout) findViewById(R.id.link1);
link2 = (RelativeLayout) findViewById(R.id.link2);
link3 = (RelativeLayout) findViewById(R.id.link3);
link4 = (RelativeLayout) findViewById(R.id.link4);
link5 = (RelativeLayout) findViewById(R.id.link5);
link6 = (RelativeLayout) findViewById(R.id.link6);
link7 = (RelativeLayout) findViewById(R.id.link7);
link1.setOnClickListener(this);
link2.setOnClickListener(this);
link3.setOnClickListener(this);
link4.setOnClickListener(this);
link5.setOnClickListener(this);
link6.setOnClickListener(this);
link7.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.link1:
linkFunction("http://changevssame.blogspot.com/2014/03/willow-cricket-hd-live-streaming.html");
break;
case R.id.link2:
linkFunction("http://changevssame.blogspot.com/2014/03/foxsports-live-streaming.html");
break;
case R.id.link3:
linkFunction("http://changevssame.blogspot.com/2014/03/sky-sports-live-streaming.html");
break;
case R.id.link4:
linkFunction("http://changevssame.blogspot.com/2014/03/ten-sports-live-streaming.html");
break;
case R.id.link5:
linkFunction("http://changevssame.blogspot.com/2014/03/star-cricket.html");
break;
case R.id.link6:
linkFunction("http://changevssame.blogspot.com/2014/03/icc-t20-world-cup-2014-live-streaming.html");
break;
case R.id.link7:
linkFunction("http://changevssame.blogspot.com/2014/03/ptv-sports.html");
break;
default:
break;
}

I will try to answer your questions but there are many fundamentals you've got to learn in order to build up a successful Streaming Application.
1. From where I can found the links to play cricket streaming ?
No idea, but this is not a SO standard question anyway.
2. Which type of links are these ?
IF you mean live streaming links, there are many types but mostly they are either HLS or RTSP.
HLS links are simple HTTP links that often end with a ".m3u8" postfix. (e.g "http://somewebsite.com/streams/hls_stream_video.m3u8")
RTSP links on the other hand, have a format like this: "rtsp://somewebsite.com/streams/an_rtsp_stream.mp4"
3. Is there any player to play this type of videos ?
Absolutely. You can do so by any means.
I'm not exactly sure by "a player" whether you mean Android API player or third-party player applications. So I'll cover both cases for you and future passengers.
I) Android API: You can do so with the help of a MediaController, a MediaPlayer and a SurafceView. The latter two are also available in a unit entity known as VideoView.
There is a code in the answer below, you can use that. But Be aware of two key points:
I-a) Using MediaPlayer is harder to implement but gives you more detailed control compared to VideoView.
I-b) If you use some code similar to the below answer Never call prepare() for network streams. Always prepareAsync(). And Always call setAudioStreamType() before prepareAsync. Otherwise you will face transient sync issues between Audio and Video when seeking on the progressbar.
II) Player Application: I have done streaming with MXPlayer and it works great.
There are some considerations to take before starting:
What protocol to choose?
Assuming you are targeting Android, I can advice you to narrow your choices down to HLS and RTSP.
You need to study them well before making a decision. But to give you a hint. HLS is preferred when functioning on lower Bandwidths.
There are many other topics like whether to choose UDP/TCP, IP-Multicast/Broadcast and so on...
Want to delve into coding and learn Video Streaming programmatically?
Go and visit this tutorial. This is the most complete zero-to-hero guide in my opinion.
Since SO lacks a thorough post on Video Streaming, maybe I will extend my answer on demand.

Follow this link :
Android Video Streaming
Below code works for me :
public static void getVideoFromHttp(String urlPath) {
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(mContext);
mediacontroller.setAnchorView(mVideoview);
// Get the URL from String VideoURL
Uri mVideo = Uri.parse(urlPath);
mVideoview.setMediaController(mediacontroller);
mVideoview.setVideoURI(mVideo);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
mVideoview.requestFocus();
mVideoview.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
mVideoview.start();
}
});
mVideoview.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
}
});
}

Try this:
private void playLive(String path){
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}

Related

Putting a sound effect in a java program [duplicate]

I'm looking to do a very simple piece of code that plays a sound effect. So far I have this code:
SoundManager snd;
int combo;
private void soundSetup() {
// Create an instance of the sound manger
snd = new SoundManager(getApplicationContext());
// Set volume rocker mode to media volume
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the samples from res/raw
combo = snd.load(R.raw.combo);
}
private void playSound() {
soundSetup();
snd.play(combo);
}
However, for some reason when I use the playSound() method, nothing happens. The audio file is in the correct location.
Is there a specific reason you are using SoundManager? I would use MediaPlayer instead, here is a link to the Android Docs
http://developer.android.com/reference/android/media/MediaPlayer.html
then it's as simple as
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.combo);
mp.start();
Make a directory called "raw/" under the "res/" directory. Drag wav or mp3 files into the raw/ directory. Play them from anywhere as above.
i have also attempted using the top answer, yet it resulted in NullPointerExceptions from the MediaPlayer when i tried playing a sound many times in a row, so I extended the code a bit.
FXPlayer is my global MediaPlayer.
public void playSound(int _id)
{
if(FXPlayer != null)
{
FXPlayer.stop();
FXPlayer.release();
}
FXPlayer = MediaPlayer.create(this, _id);
if(FXPlayer != null)
FXPlayer.start();
}

Attempt to call getDuration in wrong state: mPlayer=0x0, mCurrentState=1 How can I solve it?

I am a novice developer trying to make an audio player on android.
On Youtube (https://www.youtube.com/watch?v=hNbXrlrWzGY&list=PL9vy4y29rrd4x5pAbowit8gpjsXAai0yF&index=8),
I did the same way I implemented it at 18:19, but it was played in Youtube video, but I didn't.
I also tried applying the content here Media Player called in state 0, error (-38,0),
but the music still doesn't play.
Here is my code.
musicPlayer = new MediaPlayer();
MediaController controller = new MediaController(this);
try {
musicPlayer.setDataSource(song.getPath());
musicPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
String duration = millisecondsToString(musicPlayer.getDuration());`
What's the difference between that YouTube and the way I did it?
Thank you.
++I invoke start() in onClick()
public void onClick(View v) {
switch(v.getId()) {
case R.id.playbtn :
if(musicPlayer.isPlaying()) {
musicPlayer.pause();
playbtn.setBackgroundResource(R.drawable.resume);
} else {
musicPlayer.start();
playbtn.setBackgroundResource(R.drawable.play);
}
break;
Firstly sorry for my English.
Are you have invoked the method: player.start() ? .
If not,You need invoked it when player prepare successed.
It may be have a listener for when prepare Ready callback.
Invoke the player.start() when received the event.
Or invoke the player.autoStart() like it.
The method name maybe not to exit but maybe similar

Realtime Multiplayer Google Play Service combined with LibGDX

I am new to game development, and i'm struggling a bit with combining the google play service realtime multiplayer functionality in my LibGDX game. I do not find a lot of tutorials regarding this online.
I have downloaded the BaseGameUtils library, and everything is connected (my signIn method works), and i'm using interfaces to combine the android package with my core package.
In my AndroidLauncher, i have this code:
#Override
public void startQuickGame() {
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 1;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(MIN_OPPONENTS, MAX_OPPONENTS, 0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder((RoomUpdateListener) this);
rtmConfigBuilder.setMessageReceivedListener((RealTimeMessageReceivedListener) this);
rtmConfigBuilder.setRoomStatusUpdateListener((RoomStatusUpdateListener) this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
//prevent screen from sleeping
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Games.RealTimeMultiplayer.create(gameHelper.getApiClient(), rtmConfigBuilder.build());
}
I try to use the code in my Menu class:
#Override
protected void handleInput() {
if (Gdx.input.justTouched() && isOnBtn()) {
try {
crush.playServices.startQuickGame();
} catch (Exception e) {
e.printStackTrace();
}
gsm.set(new OnlineMultiplayerState(gsm));
dispose();
I'm not sure about how i should actually start the game?
At this point, everything just go black.
I would also like to use the code for methods like
handleSelectPlayersResult(int response, Intent data)
The problem is that when i try to define this method in my interface, it wont work because Intent only work in the Android package (not in core where my interface is).
Do you have an suggestion to how i can solve this?
Thank You!

Out Of Memory Exception occuring in android even after recycling Bitmap

i have read many threads on this topic and tried to use them in my code but i am still not able to solve it.
What i am trying to do:
Like facebook or any other app which downloads feed from server which includes image, I am also doing same and trying to display feeds and images on the image view.
What is happening:
I am able to download the feeds (in JSON) which includes URL of images and i am able to show them on ImageView.
In Emulator my MAX heap size is 64MB. I am consuming around 30MB in first 10 feeds( not sure why but this is what i get from Memory tab in Android monitor of Android Studio and Even in Android Device monitor).
I have a refresh button in my app which reloads the same feeds after removing all feeds which were earlier populated. I expected that i will be consuming the same memory or some what more. But contrary to that my memory usage got increased upto 42MB. Hence after tapping on refresh for 3 to 4 times, it is causing OutOFMemory Execption. Even if i load next 10 feed or 50 feeds at a time i am getting OutOfMemory Exception.
I know that facebook instagram and many more such apps does the same thing but not sure how they implemented the code to cover this situation.
Below is my code for populating feed
private void loadFeed(List<Feed> feedList)
{
Log.v(Constant.TAG,"Loading Feed in social feed page");
for(final Feed feed:feedList) {
LinearLayout feedBox = new LinearLayout(this);
feedBox.setOrientation(LinearLayout.VERTICAL);
FrameLayout profileDetailContainer= new FrameLayout(this);
LinearLayout profileDetailContainerParent=new LinearLayout(this);
LinearLayout profileDetailContainerChild=new LinearLayout(this);
profileDetailContainerChild.setOrientation(LinearLayout.VERTICAL);
ImageView imgProfile= new ImageView(this);
TextView txtDate= new TextView(this);
TextView txtName= new TextView(this);
ImageView imgProduct= new ImageView(this);
txtName.setText(feed.getUserFullName());
TextView txtDesciption= new TextView(this);
txtName.setTypeface(null, Typeface.BOLD);
if(feed.getDescription().length()>Constant.NUMBER_OF_DESCRIPTION_CHAR_SHOW_ON_RESULT)
{
txtDesciption.setText(feed.getDescription().substring(0,Constant.NUMBER_OF_DESCRIPTION_CHAR_SHOW_ON_RESULT)+"...");
}
else
txtDesciption.setText(feed.getDescription());
if(!IOUtil.fileExists(this,feed.getProductImageName())) {
WebRequest request = new WebRequest();
request.setUrl(Constant.ROOT_APPLICATION_URL_WITH_SEPARATOR + feed.getImgPath());
request.setParam(feed.getId() + "");
new ImageDownloadTask(this, true, feed.getProductImageName(), this).execute(request);
Log.v(Constant.TAG,"URL:"+Constant.ROOT_APPLICATION_URL_WITH_SEPARATOR+feed.getImgPath());
Picasso.with(getApplicationContext()).load(R.drawable.logo).into(imgProduct);
feedBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScreenUtility.alertException(v.getContext(),"Please wait untill product image loads");
}
});
PixyfiSession.save(feed.getId() + "", imgProduct);
PixyfiSession.save(feed.getId() + "_feed", feed);
}
else
{
ImageUtil.recycleIfPossible(imgProduct);
try {
imgProduct.setImageBitmap(ImageUtil.getLocalImage(feed.getProductImageName(),this));
FeedboxOnClickListener feedboxOnClickListener = new FeedboxOnClickListener(feed);
feedBox.setOnClickListener(feedboxOnClickListener);
} catch (FileNotFoundException e) {
Log.v(Constant.TAG,e.getMessage(),e);
}
}
if(FacebookUtil.localProfilePicExists(feed.getUserName(),this))
{
Bitmap profileImage= FacebookUtil.getLocalProfilePicture(feed.getUserName(),this);
imgProfile.setImageBitmap(profileImage);
}
else {
FacebookUtil.loadProfilePicture(feed.getUserName(),this,this);
PixyfiSession.save(feed.getUserName(),imgProfile);
imgProfile.setImageResource(R.drawable.profile);
}
try {
if(feed.getDate()==null) {
txtDate.setText(new SimpleDateFormat("dd MMM yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse(feed.getFeedDate())));
}
else {
txtDate.setText(new SimpleDateFormat("dd MMM yyyy").format(feed.getDate()));
}
} catch (ParseException e) {
Log.e(Constant.TAG,e.getMessage(),e);
}
LinearLayout.LayoutParams layoutParam= new LinearLayout.LayoutParams(140,140);
layoutParam.setMargins(5,5,0,0);
imgProfile.setLayoutParams(layoutParam);
layoutParam= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,Gravity.TOP|Gravity.LEFT);
layoutParam.setMargins(20,5,0,0);
txtName.setLayoutParams(layoutParam);
layoutParam= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,Gravity.LEFT);
layoutParam.setMargins(20,5,0,0);
txtDate.setLayoutParams(layoutParam);
profileDetailContainerParent.addView(imgProfile);
profileDetailContainerChild.addView(txtName);
profileDetailContainerChild.addView(txtDate);
profileDetailContainerParent.addView(profileDetailContainerChild);
feedBox.addView(profileDetailContainerParent);
LinearLayout.LayoutParams feedLayoutParam=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT,Gravity.CENTER_VERTICAL);
feedLayoutParam.setMargins(5,5,5,5);
imgProduct.setLayoutParams(feedLayoutParam);
txtDesciption.setLayoutParams(feedLayoutParam);
feedBox.addView(txtDesciption);
feedBox.addView(imgProduct);
feedLayoutParam=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT,Gravity.CENTER_VERTICAL);
feedLayoutParam.setMargins(0,5,0,5);
feedBox.setLayoutParams(feedLayoutParam);
feedBox.setBackgroundColor(Color.parseColor("#cccccc"));
PixyfiSession.save(feed.getId()+"_feedbox",feedBox);
imgProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PixyfiSession.save(Constant.SELECTED_USER_ID,feed.getUserName());
ScreenUtility.loadScreen(v.getContext(),UsersProfile.class,false);
}
});
this.feedContainer.addView(feedBox);
}
if(feedList.size()==Constant.FEED_SIZE_IN_ONE_REQUEST)
{
Button moreFeed= new Button(this);
moreFeed.setText("Load MOre Feed");
moreFeed.setOnClickListener(new MoreFeedButtonListener(this));
this.feedContainer.addView(moreFeed);
}
this.progressBar.setVisibility(View.INVISIBLE);
}
For reloading/refreshing the feed
this.currentPage=1;
this.recycleImages();
this.feedContainer.removeAllViews();
PixyfiSession.save(Constant.CURRENT_FEED_PAGE,this.currentPage);
this.progressBar.setVisibility(View.VISIBLE);
loadFeed();
recycleImages Method:
private void recycleImages()
{
for(int i=0;i<this.feedContainer.getChildCount();i++)
{
if(this.feedContainer.getChildAt(i) instanceof ImageView)
{
ImageView view=(ImageView)this.feedContainer.getChildAt(i);
ImageUtil.recycleIfPossible(view);
}
}
}
If you need further details on the code then please let me know.
Also is it possible to see memory usage of other apps like facebook in android device monitor?
UPDATE
ImageUtil.getLocalImage Method
public static Bitmap getLocalImage(String imageName, Context context) throws FileNotFoundException
{
Bitmap bitmap=null;
InputStream is=null;
if(IOUtil.fileExists(context,imageName)) {
is = context.openFileInput(imageName);
bitmap= BitmapFactory.decodeStream(is);
}
else {
throw new FileNotFoundException("Image file doesn't exists");
}
return bitmap;
}
I am adding the answer :
Instead of managing the view components yourself you should always prefer listview or better recycler view.
Because it help you avoid view leaks and provide better reuse of views that you already created.
i had same problem add this line to your manifest in application tag:
<application
android:largeHeap="true"
.
.
.
As Saber Safavi told do that first and then add
defaultConfig {
....
multiDexEnabled true
....
}
in your
app/build.gradle
file..
Look like you have problem with loading images. Please check your ImageUtils.getLocalImages, did you decode and load a scaled version of images into memory, or did you load original images into memory?
Follow this document from Android developer , i think it's the best tutorial for loading images efficiently in Android.
Image handling in Android is very very tricky. Better use a library which has been built to take care of the situation and complexities involved.
I prefer
UniversalImageLoader or Piccaso!
It is because you are keeping too many bitmap images in Run-time memory, try not to create too many images and try nullifying them.
Mobile devices typically have constrained system resources. Android devices can have as little as 16MB of memory available to a single application. Virtual Machine Compatibility gives the required minimum application memory for various screen sizes and densities. Applications should be optimized to perform under this minimum memory limit. However, keep in mind many devices are configured with higher limits.
I will not recommend you for the heapSize flag in android manifest. I hope you are not developing games :), Rather go for retrofit or any other image processing library if you want. I would suggest you to look at BitmapFun sample provided by Google. It is available on developer portal.
http://developer.android.com/training/displaying-bitmaps/index.html
Cheers!!

Android code for grammar based speech recognition

I am developing an Android App which requires speech to text conversion. Currently I have used Google voice search for this purpose but using google requires internet connection and moreover it gives highly inaccurate results for eg. when I say '1' it prints "when"..
Therefore, I want to define my own grammar such that when I give a voice command it searches the grammar defined by me to find the best possible match instead of searching the internet. Using grammar for speech recognition can be done easily for windows 8 phone but I want to know how I can make this work for Android phones.
Kindly take a look at below codes!..
**Using Intent:::**
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
Without Using Intent::
Step 1: Implement RecognitionListener in your class.
Step 2. Add the Below codes:
private SpeechRecognizer speech = null;
private Intent speechIntent=null;
/**
* Speech Result is used to Store the Voice Commands
*/
private ArrayList<String> speechResult;
inside onCreate() --- >
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
Trigger this after your button Click:
if (SpeechRecognizer.isRecognitionAvailable(this)) {
if(speechIntent==null ){
speechIntent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
speechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
speechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,12);
speech.startListening(speechIntent);
}else{
if(speech!=null){
speech.startListening(speechIntent);
}
}
}
Replace the onResults link this:
public void onResults(Bundle results) {
speechResult = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(speechResult!=null){
if(speechResult.size()>0 ){
String command=speechResult.get(0).toString();
}
}
}

Categories

Resources