Code-Snippets, die das Native SDK für Android verwenden

Produkt (e)
Brightcove-Player
Video Cloud
Rolle (n)
Geräte-SDK-Entwickler
Aufgaben)
Entwickeln Sie mit den Native SDKs
Thema (n)
Codebeispiele
API (s)
Wiedergabe-API
SDK
androide

In diesem Thema finden Sie eine Sammlung von Code-Snippets, die Sie während der Entwicklung mit dem SDK als Referenz verwenden können. Detailliertere Lösungen finden Sie in der Android-Player-Beispiele.

Inhaltsverzeichnis

Werbung
Analyse
Bildunterschriften
Konzepte
Inhaltssicherheit (DRM)
Live-Streams
Wiedergabe
Spielerkontrollen
Wiedergabelisten
Video-Inhalte

Steuerelemente für Android TV anpassen

Sie können der Steuerleiste für Geräte oder Android TV Schaltflächen hinzufügen. Die folgenden Schritte führen Sie durch Hinzufügen einer Vollbild-Schaltfläche zur Steuerleiste für Android TV:

  1. Öffnen Sie die Benutzerdefinierte Steuerelemente Beispiel-App Wir werden das als Ausgangspunkt verwenden. Überprüfen Sie die Beispiel-Apps README Datei für Details zum Anpassen von Playersteuerelementen.
  2. Öffnen Sie die res / Layout / Land / meine_Medienkontrolle.xml Datei in Android Studio.
  3. Kopieren Sie die Taste Element für die Vollbild Taste. Der Code sollte ähnlich aussehen:
    <Button style = "@ style / BorderlessButton" android: id = "@ id / full_screen" android: padding = "4dp" android: layout_gravity = "center_vertical" android: layout_height = "wrap_content" android: layout_width = "wrap_content" android: Sichtbarkeit = "sichtbar" android: text = "@ string / hellcove_controls_enter_full_screen" />
  4. Öffnen Sie die res / layout / my_tv_media_controller.xml Datei in Android Studio.
  5. Fügen Sie die kopierten ein Taste Element in diese Layoutdatei. Die Position der Elemente bestimmt ihre Position in der Kontrollleiste.
  6. Scrollen Sie zum Anfang des res / layout / my_tv_media_controller.xml Datei. Stellen Sie sicher, dass die style-Eigenschaft auf festgelegt ist @ style / BrightcoveControlBar.TV.Custom. Der Code sollte folgendermaßen aussehen:
    <? xml version = "1.0" codierung = "utf-8"?> <com.brightcove.player.mediacontroller.BrightcoveControlBar xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: bmc = "http://schemas.android.com/apk/res-auto" xmlns: tools = "http://schemas.android.com/tools" Werkzeuge: ignore = "Overdraw, InconsistentLayout" android: id = " @ + id / hellcove_control_bar "android: Hintergrund =" @ color / bmc_hintergrund "android: layout_width =" match_parent "android: layout_height =" wrap_content "android: padding =" 8dp "android: orientierung =" horizontal "android: layout_gravity =" bottom " style =" @ style / BrightcoveControlBar.TV.Custom ">
  7. Öffnen Sie die res / values ​​/ styles.xml Datei in Android Studio.
  8. Zum Stil Element mit a Name Wert von BrightcoveControlBar.TV.Custom, füge einen hinzu Artikel Element für die Vollbild-Taste und setzen Sie es auf was diese Dinge sind. um es anzuzeigen.
    <style name = "BrightcoveControlBar.TV.Custom"> <Elementname = "brightcove_vr_mode"> false </ item> <Elementname = "brightcove_full_screen"> true </ item> </ style>
  9. Das ist es. Führen Sie die Beispielanwendung auf einem physischen oder virtuellen Android TV-Gerät aus. Sie sollten die Vollbild-Schaltfläche in der Kontrollleiste sehen.
    Vollbild-Taste
    Vollbild-Taste

Dauer für Livestreams erhalten

Um die Dauer für einen Livestream zu erhalten, können Sie den MAX_POSITION. Dies gibt Ihnen die größte suchbare Position für einen Live-Stream (dh, am weitesten können Sie die Bildlaufleiste ziehen). Ihr Code sollte folgendermaßen aussehen:

brightcoveVideoView.getEventEmitter (). on (EventType.PROGRESS, neuer EventListener () {@Override public void processEvent (Ereignisereignis) {int duration = (int) event.properties.get (Ereignis.MAX_POSITION);}});

Abrufen der URL für Miniaturbilder

Möglicherweise möchten Sie die Miniaturbilder oder Standbilder aus Ihrer Brightcove-Bibliothek verwenden. Verwenden Sie den folgenden Code, um die URL für Ihre Bilder zu erhalten:

For Video Cloud customers using the Edge Catalog (com.brightcove.player.edge.Catalog), you can get the thumbnail URL like this:

String thumbnailUrl = video.getProperties().get("thumbnail").toString();

If you find that the thumbnail image is too small, you can get the video still image instead:

String videoStillUrl = video.getProperties().get("stillImageUri").toString();

Google Analytics

Wenn Sie den Brightcove-Player und die Katalogklasse verwenden, werden Videoanalysen automatisch erfasst und in Ihrem Video Cloud Analytics-Modul angezeigt. Für zusätzliche Messwerte können Sie Google Analytics zu Ihrer App hinzufügen.

Führen Sie die folgenden Schritte aus, um Google Analytics mit Ihrer App zu integrieren:

  1. Add the Google Services plugin to your project.
  2. Get a Google configuration file and add it to your project.
  3. Extend the Application and provide a helper method that returns your applications tracker. It should look similar to the google-services AnalyticsApplication.
  4. In a separate class which extends the BrightcovePlayer, obtain the shared tracker instance:
    // Obtain the shared Tracker instance
    AnalyticsApplication application = (AnalyticsApplication) getApplication();
    tracker = application.getDefaultTracker();
  5. Override appropriate methods to log screen changes and/or send custom events for tracking.

For detailed steps, see Google's document to Add Analytics to Your Android App.

Vollbildmodus

You can manage fullscreen mode using code.

DRM-Inhalt manuell hinzufügen

As a Brightcove Player customer, you may want to use DRM protected content from your own server. You can manually load DRM content as follows:

import com.brightcove.player.display.WidevineMediaDrmCallback;

Video video = Video.createVideo("https://storage.googleapis.com/wvmedia/cenc/h264/tears/tears.mpd");
video.getProperties().put(WidevineMediaDrmCallback.DEFAULT_URL, "https://proxy.uat.widevine.com/proxy?video_id=&provider=widevine_test");
brightcoveVideoView.add(video);
brightcoveVideoView.start();

Methoden: synchron oder asynchron?

Here are some of the asynchronous methods found in the Native Player SDK for Android:

  • Die Anfang(), seekTo() und stopPlayback() methods are asynchronous, because they emit an event for other components in the system to handle.
  • Die clear() method is synchronous with respect to updating the list, but it's asynchronous with respect to unloading the current video.

Offline-Wiedergabe mit DRM

For videos downloaded for offline playback, the download status can also be shown in the Notification Area. The notification title is set to the video title. The notification is removed if the download is paused or cancelled.

Download notification status
Laden Sie den Status Notification content text Notification icon
Herunterladen R.string.odrm_download_running - this is "Downloading…" by default

There will be a progress bar showing the percent complete.
The platform-default animated "downloading" icon - android.R.drawable.stat_sys_download
Wiederholen R.string.odrm_download_waiting_retry - this is "Waiting retry..." by default  
Gescheitert R.string.odrm_download_failed - this is "Failed!"" by default  
Fertiggestellt R.string.odrm_download_complete - this is "Saved" by default The platform-default static "downloaded" icon - android.R.drawable.stat_sys_download_done

For a status of Retry or Failed, the notification subtext will be set to an appropriate resource based on the error type. Here is the full list:

  • R.string.odrm_error_none
  • R.string.odrm_error_cannot_resume
  • R.string.odrm_error_device_not_found
  • R.string.odrm_error_file_already_exists
  • R.string.odrm_error_file_error
  • R.string.odrm_error_http_data_error
  • R.string.odrm_error_insufficient_space
  • R.string.odrm_error_too_many_redirects
  • R.string.odrm_error_unhandled_http_code
  • R.string.odrm_error_unknown

Paging mit der Wiedergabe-API

Wenn Sie Ihren Video Cloud-Inhalt über die Playback-API abrufen, können Sie den Seitenwechsel für eine Wiedergabeliste implementieren.

Verwenden Sie die folgenden Anforderungs-URL-Parameter, um durch eine Reihe von Videos in einer Wiedergabeliste zu blättern:

  • Grenze - Definiert die Anzahl der Videos, die von der Playback-API zurückgegeben werden
  • Offset - Legt die Anzahl der Videos fest, die in einer Wiedergabeliste von der Playback-API übersprungen werden sollen

The query parameters will be passed to the Catalog method as a Map object, as key-value pairs. This example returns 6 videos starting with the 10th video in the playlist:,>

Map<String, String> queryParameters = new HashMap<>();
queryParameters.put("limit", "6");
queryParameters.put("offset", "9");

Catalog catalog = new Catalog(eventEmitter, "myAccount", "myPolicy");
catalog.findPlaylistByID("myPlaylistId", null, queryParameters, myListener);

Lokale Videos abspielen

If you want to play MP4 videos that are stored locally, then you should save them in the application asset folder.

Uri video = Uri.parse("file:///android_asset/path/to/video.mp4");
brightcoveVideoView.add(Video.createVideo(video.toString()));
brightcoveVideoView.start();

Suche ohne Werbung

Sie können die Verwendung adsDisabled property for the VideoplaybackController to disable ad playback while you are seeking through a video.

To use this feature, follow these steps:

  1. Bekommen das VideoplaybackController instance from the BrightcoveVideoView.

    VideoPlaybackController playbackController = brightcoveVideoView.getPlaybackController();
  2. Disable ad playback.

    playbackController.setAdsDisabled(true);
  3. Seek to the desired time position in the current video.
  4. Resume normal ad behavior.

    playbackController.setAdsDisabled(false);

Your code should look something like this:

final VideoPlaybackController playbackController = brightcoveVideoView.getPlaybackController();
eventEmitter.on(EventType.VIDEO_DURATION_CHANGED, new EventListener() {
@Override
  public void processEvent(final Event event) {
  playbackController.setAdsDisabled(true);
  brightcoveVideoView.seekTo(10000);
  }
});

eventEmitter.on(EventType.DID_SEEK_TO, new EventListener() {
@Override
  public void processEvent(final Event event) {
  playbackController.setAdsDisabled(false);
  }
});

Einstellen der Puffergröße

You may consider increasing the buffer length to eliminate buffering in the player if the delivery of the next segment is delayed from the CDN. But, you may not be able to do anything better manually that HLS already does.

HLS is designed to play right away and drop quality if it can't keep up. This way, it does not need to preload a buffer. If it can't keep up, it will load as much of the video as it can at the best quality to prevent interruption.

That being said, if you are using the ExoPlayer 1 implementation, you can control the following:

For example, if you want to set the buffer length to 120 seconds, you could set minBufferMs to 120 * 1000.

Untertitel und Themen einstellen

Derzeit ist die BrightcoveCaptionPropertiesActivity is set in the Brightcove Player SDK’s manifest file, so developers don’t need to specify it in their applications:

<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.brightcove.player"
android:versionCode="1"
android:versionName="1.0">

<application>
<!-- If we don't register this Activity in the Manifest, apps using the SDK will crash when they try to access it. -->
<!-- During the app's build process, this manifest will be merged with the app-level one. -->
<activity android:name="com.brightcove.player.captioning.BrightcoveCaptionPropertiesActivity"/>
</application>
</manifest>

Die BrightcoveCaptionPropertiesActivity will inherit the platform default theme, as long as you set themes for your app at the <Aktivität> level in your app’s manifest.

If you set a single app theme at the <Anwendung> level, then the BrightcoveCaptionPropertiesActivity will inherit the properties of this application-level theme. For some themes, this can cause the activity to look oddly styled or even illegible.

In those cases, you should specify the BrightcoveCaptionPropertiesActivity in your own manifest and apply a theme there, like so:

<activity
android:name="com.brightcove.player.captioning.BrightcoveCaptionPropertiesActivity"
android:theme="@style/MyCustomCaptionSettingsTheme"/>

Festlegen von Standardtiteln

If your video uses multiple language captions, you can programmatically set a default language when playback starts. Your code should look similar to this:

brightcoveVideoView.getEventEmitter().once(EventType.CAPTIONS_LANGUAGES, new EventListener() {
@Override
public void processEvent(Event event) {
  brightcoveVideoView.setClosedCaptioningEnabled(true);
  brightcoveVideoView.setSubtitleLocale("fr");
  }
});

Einstellen der Peak-Bitrate

To help you implement a bitrate selector in your player, you can use the following code to set the peak bitrate:

((ExoPlayerVideoDisplayComponent) videoView.getVideoDisplay()).setPeakBitrate(bitRate);

Einstellen des VR Goggles Modus für 360 ° Videos

When playing a 360° video, users can select the Video 360 button on the control bar to switch to VR Goggles mode. If you are using either the BrightcovePlayer or BrightcovePlayerFragment activity, then the screen orientation will change to landscape when VR Goggles mode is enabled.

If you are using a custom activity, then you will need to add the following:

brightcoveVideoView.getEventEmitter().on(EventType.CHANGE_ORIENTATION, new EventListener() {
@Override
public void processEvent(Event event) {
  int orientation = event.getIntegerProperty(Event.REQUESTED_ORIENTATION);
  setRequestedOrientation(orientation);
  }
});

Video Standbilder anzeigen / ausblenden

The default behavior when retrieving videos from your Video Cloud library is to display the video still image until playback begins.

Hiding the video still image

If you are autoplaying the video, you may want to hide the video still image. To do this, you can listen for the SET_VIDEO_STILL event and prevent the default behavior as follows:

brightcoveVideoView.getEventEmitter().on(EventType.SET_VIDEO_STILL, new EventListener() {
@Override
public void processEvent(Event event) {
  event.preventDefault();
  event.stopPropagation();
  }
});

Showing the video still image

You can show the video still at any time by emitting a SET_VIDEO_STILL Ereignis mit a VIDEO_STILL property set to the URI of the video still.

Starten der Wiedergabe in der Mitte eines Videos

Sometimes, you may need to start playback from somewhere in the middle of the video. To do this, you can call BrightCoveVideoView.seekTo() before starting playback.

catalog.findVideoByID(getString(R.string.videoId), new VideoListener() {
@Override
public void onVideo(Video video) {
  Log.v(TAG, "onVideo: video = " + video);

  brightcoveVideoView.getEventEmitter().on(EventType.DID_SET_VIDEO, new EventListener() {
  @Override
  public void processEvent(Event event) {
    brightcoveVideoView.seekTo(60000);
    brightcoveVideoView.start();
    }
  });
  brightcoveVideoView.add(video);
  brightcoveVideoView.pause();
  }
});

Videos austauschen

This example shows one approach for swapping videos in the player.

Using single videos

Da der clear() method is asynchronous when unloading the current video, you need to wait before adding a new video to the player. Here are two options.

Verwenden einer Wiedergabeliste

If you are working with a playlist, keep in mind that calling the clear() method removes all the elements of the playlist. So, you may get an IndexOutOfBounds exception when trying to jump to the first video in the playlist.

Instead, you can try something like this:

brightcoveVideoView.pause();
brightcoveVideoView.stopPlayback();
brightcoveVideoView.setCurrentIndex(0);

Zwischen den Videos in einer Playlist wechseln

If you are using a playlist, you can use the following code to switch between videos in the playlist:

private void setupControls(List<Video> videos) {
previousVideoButton = (Button) findViewById(R.id.previous_video_button);
nextVideoButton = (Button) findViewById(R.id.next_video_button);

if (videos != null) {
previousVideoButton.setEnabled(false);
previousVideoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
	int index = brightcoveVideoView.getCurrentIndex();
	int size = brightcoveVideoView.getList().size();
	previousVideoButton.setEnabled(index > 1);
	nextVideoButton.setEnabled((index + 1) < size);

	if (index > 0) {
		brightcoveVideoView.setCurrentIndex(index - 1);
	}
}
});

nextVideoButton.setEnabled(videos.size() > 1);
nextVideoButton.setOnClickListener(new View.OnClickListener() {
  public void onClick(View view) {
	  int index = brightcoveVideoView.getCurrentIndex();
	  int size = brightcoveVideoView.getList().size();
	  previousVideoButton.setEnabled(index >= 0);
	  nextVideoButton.setEnabled((index + 2) < size);

	  if ((index + 1) < size) {
		  brightcoveVideoView.setCurrentIndex(index + 1);
	  }
  }
});
}
}

Arbeiten mit Lautstärkeregelung

You can programmatically mute or unmute the player. Brightcove recommends using the BrightcoveExoPlayerVideoView whenever possible.

BrightcoveExoPlayerVideoView

Bei Verwendung der BrightcoveExoPlayerVideoView, you can programmatically mute or unmute the player by doing the following:

float volume = 100;
...
brightcoveVideoView.getEventEmitter().on(EventType.DID_SET_VIDEO, new EventListener() {
@Override
public void processEvent(Event event) {
	setMute(true);
	brightcoveVideoView.start();
}
});
...
private void setMute(boolean mute) {
volume = mute ? 0 : 100;
Map properties = new HashMap<>();
properties.put(Event.VOLUME, volume);
brightcoveVideoView.getEventEmitter().emit(EventType.SET_VOLUME, properties);
},>

BrightcoveVideoView

If you need to use the BrightcoveVideoView, which uses Android's Media Player, you can programmatically mute or unmute the player with the following code:

float volume = 100;
...
brightcoveVideoView.getEventEmitter().on(EventType.DID_SET_VIDEO, new EventListener() {
@Override
public void processEvent(Event event) {
	setMute(true);
	brightcoveVideoView.start();
}
});
...
private void setMute(boolean mute) {
volume = mute ? 0 : 1;
Map<String, Object> properties = new HashMap<>();
properties.put(Event.LEFT_VOLUME, volume);
properties.put(Event.RIGHT_VOLUME, volume);
brightcoveVideoView.getEventEmitter().emit(EventType.SET_VOLUME, properties);
}