Unable to play live stream on chromecast from android sender app - android

I am using CastCompanionLibrary-android in my app and following CastVideos-android to play live streams on chromecast. Now the streaming of video works fine on my local player but when it comes to cast that video, it wont play. Rather it just show me my registered receiver app name and on sender app the VideoCastControllerActivity opens with only a loader which wont end.
I have registered both my receiver app (Styled Media Receiver) and the device on Google chrome cast console. Also, I tried to debug the receiver app, it show nothing on the debugger or in console.
Here is the code snippet of my sender app:
private void initMediaRouter() {
BaseCastManager.checkGooglePlayServices(this);
mCastManager = VideoCastManager.getInstance();
MediaMetadata mediaMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE); //also tried MediaMetadata.MEDIA_TYPE_GENERIC
mediaMetadata.putString(MediaMetadata.KEY_TITLE, channel.getChannelName());
mediaMetadata.putString(MediaMetadata.KEY_SUBTITLE, channel.getCatName());
info = new MediaInfo.Builder(channel.getHttpStream())
.setMetadata(mediaMetadata)
.setContentType("Video/*")
.setStreamType(MediaInfo.STREAM_TYPE_LIVE)
.build();
castConsumer = new CastConsumer();
mCastManager.addVideoCastConsumer(castConsumer);
}
this function is called on the player activity's OnCreate() function.
The Listener (I'm getting true value for wasLaunched param)
private class CastConsumer extends VideoCastConsumerImpl {
#Override
public void onApplicationConnected(ApplicationMetadata appMetadata, String sessionId, boolean wasLaunched) {
mCastManager.startVideoCastControllerActivity(PlayerActivity.this, info, 0, true);
}
}
And in the onCreate() function of Application:
String applicationId = getString(R.string.cast_app_id);
CastConfiguration options = new CastConfiguration.Builder(applicationId)
.enableAutoReconnect()
.enableCaptionManagement()
.enableDebug()
.enableLockScreen()
.enableNotification()
.enableWifiReconnection()
.setCastControllerImmersive(true)
.setLaunchOptions(false, Locale.getDefault())
.addNotificationAction(CastConfiguration.NOTIFICATION_ACTION_PLAY_PAUSE, true)
.addNotificationAction(CastConfiguration.NOTIFICATION_ACTION_DISCONNECT, true)
.build();
VideoCastManager.initialize(this, options);
can you please tell me where i am going wrong? Thanks.

The content type might be an issue. Try properly setting it to something like video/mp4 if that's the case.

Related

Google Android speech capture timeout

Just a quick question about the Google speech capture inbuilt on most Android devices (not the cloud service) - see the attached image. Is there any way, either programatically or via the settings, to control how long it waits until it asks you to try again? The 'complete silence' fields in the RecognizerIntent don't seem to make any difference. On certain devices it times out very quickly and the user doesn't have enough time to start speaking.
This is the code in my test app:
public void StartSpeechToText(ISpeechResultCallback callback)
{
string rec = global::Android.Content.PM.PackageManager.FeatureMicrophone;
if (rec == "android.hardware.microphone")
{
MainActivity activity = MainActivity.CurrentActivity;
activity.Callback = callback;
var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
//var voiceIntent = new Intent(RecognizerIntent.ActionVoiceSearchHandsFree);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Speak now");
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000);
voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default);
activity.StartActivityForResult(voiceIntent, VOICE);
}
}

How to put media buttons on the lockscreen with ExoPlayer

I am using ExoPlayer (https://github.com/google/ExoPlayer) and custom notifications.
I want to access my music player from lock screen and headphone like in google play music and wync.
Please help me.
For playback controls on the lock screen you need to do a MediaStyle notification.
If you want to have an artwork as the lockscreen background you need to support MediaSession and maintain the metadata of the session properly:
new MediaMetadata.Builder(track)
.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap)
.putBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON, bitmap)
.build();
I am also using Exoplayer with PlayerNotificationManager, And I used MediaSessionConnector and TimelineQueueNavigator to build notifications for the lock screen and background image for the lock screen.
Here, is my question with the Exoplayer team which is resolved for android 11 and above, regarding how to use MediaSessionConnector:
Why PlayerNotificationManager not showing Notification on startForeground in Android 11(R)?
Now, I just added a bitmap (using putParcelable()) for the current session track for MediaDescriptionCompact which will be set to the current MediaSession internally.
Here is the code for that:
val mediaSession = MediaSessionCompat(serviceContext, "DPS_APP")
mediaSession.isActive = true
mediaSessionConnector = MediaSessionConnector(mediaSession).also {
it.setQueueNavigator(
object : TimelineQueueNavigator(mediaSession) {
override fun getMediaDescription(
player: Player,
windowIndex: Int
): MediaDescriptionCompat {
val data: MediaMetaData =
getEmptyOfNullMedia(player)
isBitmapAvailable(getCurrentMediaArt(data))
val extras = Bundle().apply {
putString(
MediaMetadataCompat.METADATA_KEY_TITLE,
getCurrentTitle(data)
)
putString(
MediaMetadataCompat.METADATA_KEY_ARTIST,
getMediaTitle(data)
)
putParcelable(
MediaMetadataCompat.METADATA_KEY_ALBUM_ART,
sessionCurrentBitmap
)
}
return MediaDescriptionCompat.Builder()
.setIconBitmap(sessionCurrentBitmap)
.setExtras(extras)
.build()
}
it.setPlayer(mPlayer)
}
Here is a small brief on that how to refresh or invalidate MediaSession in the given below issue on GitHub:
https://github.com/google/ExoPlayer/issues/5494

How to use native Equalizer in the App

I am using the following code to open the Equalizer in the App.
Intent intent = new Intent( );
intent.setAction("android.media.action.DISPLAY_AUDIO_EFFECT_CONTROL_PANEL");
if (intent.resolveActivity( getActivity().getPackageManager()) != null )
{
startActivityForResult( intent , 100 );
}
else
{
JBUtils.getInstance().showCustomToast( getActivity() , R.string.equalizer_notfound);
}
And added the permission
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
After user changes the Equalizer settings how to apply equalizer settings in the currently playing audio file.We are using the Exoplayer for playing the music file.
Thanks in Advance.
Please look at this issue (closed):
https://github.com/google/ExoPlayer/issues/252
There's an interesting example about using Equalizer in ExoPlayer.
I didn't try it yet but it seems an interesting starting point to integrate standard Equalizer in ExoPlayer.
Let me know if it works!
Here is the example I would start with:
audioRenderer = new MediaCodecAudioTrackRenderer(......){
private Equalizer equalizer;
#Override
public void onAudioSessionId ( int audioSessionId){
releaseEqualizer();
equalizer = new Equalizer(...,audioSessionId);
// Configure equalizer here.
equalizer.setEnabled(true);
}
#Override
public void onDisabled () {
releaseEqualizer();
}
private void releaseEqualizer () {
if (equalizer != null) {
equalizer.release();
equalizer = null;
}
}
};
Moreover there seems to be some issue with the equalizer. You can try to enable the workaround (disabled by default) in AudioTrack, setting the following flag to true:
public static boolean enablePreV21AudioSessionWorkaround = false;
You have to provide the your package name and current Media Player audio session id as extra before starting the activity. Add the below code before calling startActivityForResult.
intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, player.getAudioSessionId());
where player is an instance of MediaPlayer.

Android Chromecast Companion Library - subtitle toggle button

I'm using the Companion library for casting video from my app to the Chromecast.
Is there any way ho I can add the subtitles / closed captions toggle button so the user will be able to turn them on and off?
I'm reading their documentation where I can see, how is possible to set the subtitle URL
MediaTrack englishSubtitle = new MediaTrack.Builder(1 /* ID */,
MediaTrack.TYPE_TEXT)
.setName("English Subtitle")
.setSubtype(MediaTrack.SUBTYPE_SUBTITLE)
.setContentId("https://some-url/caption_en.vtt")
/* language is required for subtitle type but optional otherwise */
.setLanguage("en-US")
.build();
But no words about where I should handle the show / hide actions.
Do you have any suggestions how I can add the toggle button and handle show / hide actions?
I'm using the VideoCastManager which is using the VideoCastControllerActivity from the casting library.
This is my CastConfiguration
// Build a CastConfiguration object and initialize VideoCastManager
CastConfiguration options = new CastConfiguration.Builder(MyAppConfig.CHROMECAST_APP_ID)
.enableAutoReconnect()
.enableCaptionManagement()
.enableDebug()
.enableLockScreen()
.enableNotification()
.enableWifiReconnection()
.setCastControllerImmersive(true)
.setLaunchOptions(false, Locale.getDefault())
.setNextPrevVisibilityPolicy(CastConfiguration.NEXT_PREV_VISIBILITY_POLICY_DISABLED)
.addNotificationAction(CastConfiguration.NOTIFICATION_ACTION_REWIND, false)
.addNotificationAction(CastConfiguration.NOTIFICATION_ACTION_PLAY_PAUSE, true)
.addNotificationAction(CastConfiguration.NOTIFICATION_ACTION_DISCONNECT, true)
.setForwardStep(10)
.build();
// Google Chrome Cast initialization of the VideoCastManager that is a helper class from the CasCompanionLibrary
// that helps us deal with the flow of communicating with chromecast
VideoCastManager.
initialize(this, options)
.setVolumeStep(MyAppConfig.VOLUME_INCREMENT);
And there I'm creating the MediaInfo
MediaMetadata mediaMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);
mediaMetadata.addImage(new WebImage(Uri.parse(MyAppConfigBase.IMAGE_API_ENDPOINT + movieVideoItem.getImages().getKeyart())));
mediaMetadata.addImage(new WebImage(Uri.parse(MyAppConfigBase.IMAGE_API_ENDPOINT + movieVideoItem.getImages().getKeyart())));
mediaMetadata.putString(MediaMetadata.KEY_TITLE, movieVideoItem.getTitle());
mediaMetadata.putString(MediaMetadata.KEY_SUBTITLE, movieVideoItem.getDescription());
mediaMetadata.putString("movie-urls", url);
mediaMetadata.putString("content-type", movieVideoItem.getContent().getHighRes().getType());
MediaTrack englishSubtitle = new MediaTrack.Builder(1 /* ID */, MediaTrack.TYPE_TEXT)
.setName("English Subtitle")
.setSubtype(MediaTrack.SUBTYPE_CAPTIONS)
.setContentId(closedCaptionsUrl)
/* language is required for subtitle type but optional otherwise */
.setLanguage("en-US")
.build();
List tracks = new ArrayList();
tracks.add(englishSubtitle);
MediaInfo mediaInfo = new MediaInfo.Builder(url)
.setStreamDuration(movieVideoItem.getDuration())
.setStreamType(MediaInfo.STREAM_TYPE_NONE)
.setContentType(type)
.setMetadata(mediaMetadata)
.setMediaTracks(tracks)
.setCustomData(customData)
.build();
You need to do the following:
Make sure your MediaInfo items have tracks info.
Make sure that tracks are enabled in the settings and enable the support for tracks when you configure CastVideoManager.
Register a OnTracksSelectedListener listener in your, say, activity so that when tracks change, your activity can be notified.
4.Add a button to your activity and upon a click on the button, call a method like the following.
private void showTracksChooserDialog()
throws TransientNetworkDisconnectionException, NoConnectionException {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(DIALOG_TAG);
if (prev != null) {
transaction.remove(prev);
}
transaction.addToBackStack(null);
// Create and show the dialog.
TracksChooserDialog dialogFragment = TracksChooserDialog
.newInstance(mCastManager.getRemoteMediaInformation());
dialogFragment.show(transaction, DIALOG_TAG);
}
This will open a (fragment) dialog that shows the current text and audio tracks and allows the user to select one. When one is selected and Ok is pressed in that dialog, the listener that you had registered in the previous step is called and then you can enable the track in your listener.
Make sure you remove the listener when you leave your activity.

How to cast media to default media receiver of the Chromecast device?

Trying to cast media to default media receiver of the Chromecast from android app, but it doesn't cast at all. Following is the code snippet using to find the routes :
MediaRouteSelector selector = new MediaRouteSelector.Builder()
.addControlCategory(CastMediaControlIntent
.categoryForRemotePlayback(CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID))
.build();
Then, it will show the Chromecast device within the WiFi and running the following code when the device is selected :
MediaRouter.RouteInfo route = adapter.getItem(position).routeInfo;
// select the route for usage
route.select();
// send the play control request with the video uri
route.sendControlRequest(
new Intent(MediaControlIntent.ACTION_PLAY)
.setDataAndType(videoUri, "video/mp4")
.addCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK),
new MediaRouter.ControlRequestCallback() {
#Override
public void onError(String error, Bundle data) {
super.onError(error, data);
}
#Override
public void onResult(Bundle data) {
super.onResult(data);
}
}
);
It can't cast the media to the device. Any suggestions ?
It seems like you are not using the Cast SDK but using the Media Route Provider. I don't see any session being set up; you might want to look at the democastplayer sample code that is distributed along with the Android SDK (under SDK folder, go to extras/google/google_play_service/samples/cast/democastplayer). In that sample, look at the MrpCastPlayerActivity class.

Categories

Resources