La siguiente sección describe cómo realizar las tareas más comunes usando TritonMobileSdk. El paquete del SDK incluye un proyecto de ejemplo de Xcode que muestra las características disponibles y muestra cómo integrar el SDK en una aplicación de streaming.
Configure su región
Cuando se carga el SDK, obtiene su configuración de emisora de nuestros servicios de aprovisionamiento. Para acelerar el proceso, contamos con servidores de aprovisionamiento en diversas regiones, incluidas América del Norte, Europa y Asia. Para la obtención de mejores resultados, utilice los servidores de aprovisionamiento que se encuentran más cerca de sus estaciones.
La región de aprovisionamiento predeterminada es América del Norte; para usar una de las otras regiones, especifíquela según se observa en el siguiente ejemplo, en el que se utiliza "AP" (Asia).
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"MOBILEFM_AACV2",
SettingsPlayerServicesRegion: @"AP", // AP = Asia | EU = Europe | Omit this configuration option for North America
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];
Autoplay
Por motivos de medición, así como por la experiencia del usuario, se desaconseja encarecidamente el uso de la reproducción automática. La reproducción automática se define como la reproducción de la estación/stream sin que ninguna interacción del usuario inicie la reproducción. Si implementa una estrategia de reproducción automática, debe agregar la autoplay = 1
valor para el SettingsStreamParamsExtraKey
al llamar al objeto play
en el SDK.
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"MOBILEFM_AACV2",
SettingsEnableLocationTrackingKey : @(YES),
SettingsStreamParamsExtraKey : @{@"autoplay": @"1",
@"age": @"30"}
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];
Reproducir una estación
La funcionalidad de stream se ofrece a través de TritonPlayer
Clase. Para poder reproducir, debe proporcionar la configuración de su estación; Como mínimo, proporcione el nombre de la estación y del broadcaster y el montaje. Se admiten los montajes HLS. Contacte a Triton Digital si no tiene esta información. Consulte la referencia de la API para otras configuraciones disponibles.
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"MOBILEFM_AACV2",
SettingsDebouncingKey: @(0.75) // optional debouncing for the Play action, in seconds : default value is 0.2
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];
Cambiar de estación
Al cambiar de estación, necesita proporcionar las configuraciones de la nueva estación. Use el método -updateSettings:
para configurarla. Esto anulará las configuraciones anteriores pero solo será efectivo la próxima vez que el reproductor se detenga y vuelva a reproducir.
// Stop previous stream
[self.tritonPlayer stop];
...
// Configure and play the new station
NSDictionary *settings = @{SettingsStationNameKey : @"WMSC_S01",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"WMSC_S01AAC"
};
[self.tritonPlayer updateSettings:settings];
[self.tritonPlayer play];
Como alternativa, puede recrear el TritonPlayer cada vez que cambia de estación, pero se recomienda el procedimiento detallado arriba.
Cambiar la velocidad de reproducción de podcasts
Para cambiar la velocidad de reproducción de un podcast, use changePlaybackRate
con un valor float como argumento de velocidad.
Ejemplo:
(void)setPlaybackRate:{
[self.tritonPlayer changePlaybackRate:1.5];
}
... cambiaría la reproducción a 1,5 veces la velocidad original.
Transmita mientras está silenciado
Puede configurar el comportamiento del stream mientras el reproductor está silenciado.
SettingsStreamWhileMuted
(Objeto). Requerido: No.
Utilice este objeto para habilitar o deshabilitar la reproducción continua de la transmisión cuando el usuario silencia el audio. El valor predeterminado es NO.
Opciones:
NO
- Desactivado (el stream se detiene cuando se silencia)YES
- Habilitado (la transmisión continúa cuando se silencia, pero el usuario no oye el audio)
Ejemplo de código:
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"MOBILEFM_AACV2",
SettingsStreamWhileMuted: @(NO) //Steam will be stopped when muted.
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];
Audiencia objetivo para anuncios de audio
Con el fin de direccionar su audiencia con anuncios de audio (y los respectivos banners complementarios), debe transferir los parámetros de direccionamiento a las configuraciones de TritonPlayer. Suponga que quiere orientar su programación a hombres de 30 años de edad, y proporcione sus coordenadas de ubicación:
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"MOBILEFM_AACV2",
SettingsEnableLocationTrackingKey : @(YES),
SettingsStreamParamsExtraKey : @{@"gender": @"m",
@"age": @"30"}
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];
Si seleccionó SettingsEnableLocationTrackingKey
sea SÍ, utilizará CLLocationManager
para proporcionar la ubicación del usuario (Vea "Rastreo de ubicación"). Los otros parámetros (incluida la ubicación manual) se especifican en un diccionario disponible en SettingsStreamParamsExtraKey
. Para ver todos los parámetros de direccionamiento disponibles, consulte la Guía de streaming de Triton Digital.
Puede agregar encabezados de segmento DMP (como se describe en la Especificación técnica de publicidad) para streaming en directo, podcast y on demand agregando lo siguiente a la configuración del reproductor (utilizando ejemplos de DMP permutivos y de Adobe):
SettingsDmpHeadersKey : @{@"permutive": @[@1234,@5679], @"adobe": @[@4321,@8765]},
Por ejemplo:
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"MOBILEFM_AACV2",
SettingsDmpHeadersKey : @{@"permutive": @[@1234,@5679], @"adobe": @[@4321,@8765]},
SettingsDebouncingKey: @(0.75) // optional debouncing for the Play action, in seconds : default value is 0.2
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];
Autorización con token (con autofirma)
Para poder recrear los tokens en la reconexión de trabajo, se requiere cualquiera de los siguientes parámetros:
StreamParamExtraAuthorizationSecretKey
StreamParamExtraAuthorizationKeyId
Si se completan todos los parámetros, entonces no tiene que generar el token usted mismo (aunque puede hacerlo si lo desea).
// Create the targeting parameters
NSDictionary *targetingParams = @{@"gender": @"m",
@"age": @"30"
};
// Create the authorization token
NSString *token = [TDAuthUtils createJWTTokenWithSecretKey:@"MySecretKey"
andSecretKeyId:@"MySecretKeyId" andRegisteredUser:YES andUserId:@"foo@bar.com" andTargetingParameters:targetingParams];
// Create the player settings.
NSDictionary *settings = @{SettingsStationNameKey : @"BASIC_CONFIG",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : self.playerViewController.mountName,
SettingsEnableLocationTrackingKey : @(YES),
SettingsStreamParamsExtraKey : @{@"banners": @"300x50,320x50"},
SettingsTtagKey : @[@"mobile:ios", @"triton:sample"],
StreamParamExtraAuthorizationSecretKey: @"4ToEMVkOK1sThhsw",
StreamParamExtraAuthorizationUserId: @"",
StreamParamExtraAuthorizationKeyId: @"DG83J",
StreamParamExtraAuthorizationRegisteredUser: @(YES),
};
[self.tritonPlayer updateSettings:settings];
}
// Create the player.
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
[self.tritonPlayer play];
Recibir metadatos de stream (puntos de referencia)
Una vez que el reproductor está haciendo streaming, es capaz de recibir puntos de referencia con metadatos de stream (por ejemplo, canción que se está reproduciendo actualmente, metadatos de anuncios, etc.). Para recibir puntos de referencia, debe implementar el -player:didReceiveCuePointEvent:
en la clase que será el delegado de TritonPlayer. CuePointEvent.h
define todas las constantes de tipos de puntos de referencia y claves para recuperar su información.
@interface ViewController() <TritonPlayerDelegate>
@end
@implementation ViewController
...
- (void)viewDidLoad {
[super viewDidLoad];
...
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
}
...
[self.tritonPlayer play];
...
- (void)player:(TritonPlayer *)player didReceiveCuePointEvent:(CuePointEvent *)cuePointEvent {
// Check if it's an ad or track cue point
if ([cuePointEvent.type isEqualToString:EventTypeAd]) {
// Handle ad information (ex. pass to TDBannerView to render companion banner)
} else if ([cuePointEvent.type isEqualToString:EventTypeTrack]) {
NSString *currentSongTitle = [inNowPlayingEvent.data objectForKey:CommonCueTitleKey];
NSString *currentArtistName = [inNowPlayingEvent.data objectForKey:TrackArtistNameKey];
NSString *currentAlbumName = [inNowPlayingEvent.data objectForKey:TrackAlbumNameKey];
// Do something with track data (update interface, notify user etc.)
}
}
...
@end
Mostrar un banner complementario In-Stream (sincronizar banner)
@interface ViewController() <TritonPlayerDelegate>
@property (strong, nonatomic) TDSyncBannerView *adBannerView;
@end
@implementation ViewController
...
- (void)viewDidLoad {
[super viewDidLoad];
...
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
// Create and configure a 320x50 sync banner with a fallback size of 300x50
self.adBannerView = [[TDSyncBannerView alloc] initWithWidth:320 andHeight:50 andFallbackWidth:300 andFallbackHeight:50];
[self.view addSubview:self.adBannerView];
}
...
- (void)player:(TritonPlayer *)player didReceiveCuePointEvent:(CuePointEvent *)cuePointEvent {
if ([cuePointEvent.type isEqualToString:EventTypeAd]) {
[self.adBannerView loadCuePoint:cuePointEvent];
}
...
}
...
Mostrar un anuncio intersticial
Los anuncios intersticiales (antes y durante el podcast) son anuncios a pantalla completa que aparecen en una aplicación. Por lo general se muestran en los puntos de transición naturales de la aplicación, como antes y después de reproducir o cambiar de estación de radio.
// Create a TDAdRequestBuilder to build the request string
TDAdRequestURLBuilder *request = [TDAdRequestURLBuilder builderWithHostURL:kRequestUrl];
request.stationId = 12345;
// Create a TDInterstitialAd
self.interstitial = [[TDInterstitialAd alloc] init];
// Create a TDAdLoader to load the ad from the request
self.adLoader = [[TDAdLoader alloc] init];
[self.adLoader loadAdWithBuilder:requestBuilder completionHandler:^(TDAd *loadedAd, NSError *error) {
if (error) {
// Handle error
} else {
// Load the ad into the interstitial
[self.videoInterstitial loadAd:loadedAd];
}
}
];
Una vez cargado el anuncio intersticial, debe aparecer a la hora correcta. La aplicación debe revisar si el anuncio intersticial está cargado antes de intentar mostrarlo. Si -loaded
no devuelve SÍ, el anuncio no se mostrará. Cuando aparece un anuncio intersticial, se debe pasar un controlador de vistas. Será el controlador de vistas de presentación del anuncio intersticial.
- (void)playStation {
if ([self.interstitial loaded]) {
[self.interstitial presentFromViewController:self];
}
// Rest of method logic
}
Puede agregar un temporizador de cuenta regresiva opcional para que se muestre en un anuncio intersticial. Para ello, habilite la CountdownDisplay
como se muestra en el ejemplo intersticial de video a continuación:
// Create a TDAdRequestBuilder to build the request string
TDAdRequestURLBuilder *request = [TDAdRequestURLBuilder builderWithHostURL:kRequestUrl];
request.stationId = 12345;
// Create a TDInterstitialAd
self.videoInterstitial = [[TDInterstitialAd alloc] init];
self.videoInterstitial.enableCountdownDisplay = TRUE;
// Create a TDAdLoader to load the ad from the request
self.adLoader = [[TDAdLoader alloc] init];
[self.adLoader loadAdWithBuilder:requestBuilder completionHandler:^(TDAd *loadedAd, NSError *error) {
if (error) {
// Handle error
} else {
// Load the ad into the interstitial
[self.videoInterstitial loadAd:loadedAd];
}
}
];
Puede agregar encabezados de segmento DMP (como se describe en la Especificación técnica de publicidad) a los anuncios intersticiales de la siguiente manera (utilizando ejemplos de DMP Permutive y Adobe):
requestBuilder.dmpSegments = @{@"permutive": @[@1234,@5679], @"adobe": @[@4321,@8765]}
Por ejemplo:
// Create a TDAdRequestBuilder to build the request string
TDAdRequestURLBuilder *requestBuilder = [TDAdRequestURLBuilder builderWithHostURL:kRequestUrl];
//Add DMP Segments
requestBuilder.dmpSegments = @{@"permutive": @[@1234,@5679], @"adobe": @[@4321,@8765]};
requestBuilder.stationId = 12345;
// Create a TDInterstitialAd
self.interstitial = [[TDInterstitialAd alloc] init];
// Create a TDAdLoader to load the ad from the request
self.adLoader = [[TDAdLoader alloc] init];
[self.adLoader loadAdWithBuilder:requestBuilder completionHandler:^(TDAd *loadedAd, NSError *error) {
if (error) {
// Handle error
} else {
// Load the ad into the interstitial
[self.videoInterstitial loadAd:loadedAd];
}
}
];
TTags personalizadas - Reproductor
TTags personalizadas (p. ej., mobile:ford
) se puede aplicar a las URL de streaming agregando una matriz al parámetro settings SettingsTtagKey
.
Ejemplo de TTags personalizadas - Reproductor
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsTtagKey : @[@"mobile:ios",@"chips:salsa"],
SettingsMountKey : @"MOBILEFM_AACV2"
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];
TTags personalizadas - Anuncio intersticial
TTags personalizadas (p. ej., mobile: ford
) se puede aplicar a las URL de anuncios intersticiales agregando las NSArray TTags en la TDAdRequestURLBuilder
.
TTags personalizadas - Ejemplo de anuncio intersticial
// Create a TDAdRequestBuilder to build the request string
TDAdRequestURLBuilder *request = [TDAdRequestURLBuilder builderWithHostURL:kRequestUrl];
request.stationId = 12345;
request.TTags = @[ "mobile:ios", "cola:diet" ];
// Create a TDInterstitialAd
self.interstitial = [[TDInterstitialAd alloc] init];
// Create a TDAdLoader to load the ad from the request
self.adLoader = [[TDAdLoader alloc] init];
[self.adLoader loadAdWithBuilder:requestBuilder completionHandler:^(TDAd *loadedAd, NSError *error) {
if (error) {
// Handle error
} else {
// Load the ad into the interstitial
[self.videoInterstitial loadAd:loadedAd];
}
}
];
ID de oyente múltiple
Proporciona una manera de enviar varios identificadores de usuario o dispositivo, además del ID de oyente principal (lsid
parámetro). Este último sigue siendo utilizado por Triton para la limitación de frecuencia, medición, etc., mientras que las otras ID se pueden proporcionar a plataformas de demanda de terceros para mejorar la monetización.
Los valores de StreamParamExtraListenerIdType
Son:
ppid
idfa
gaid
app
El valor de StreamParamExtraListenerIdValue
puede ser lo que tú decidas.
Ejemplo:
NSDictionary *settings = @{SettingsStationNameKey : @"BASIC_CONFIG",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"TRITONRADIOMUSIC",
SettingsEnableLocationTrackingKey : @(YES),
SettingsStreamParamsExtraKey : @{@"banners": @"300x50,320x50"},
SettingsTtagKey : @[@"mobile:ios", @"triton:sample"],
StreamParamExtraListenerIdType: @"idfa",
StreamParamExtraListenerIdValue: @"triton-app-id",
};
[self.tritonPlayer updateSettings:settings];
[self.tritonPlayer play];
Baja demora con almacenamiento adaptable
Cuando se configura en -1 / AUTO MODE
el SDK usa una pequeña ventana de búfer (dos segundos) en la conexión inicial, lo que reduce la cantidad de demora entre la reproducción y el tiempo real. (Esto resulta útil para eventos deportivos, concursos en vivo, etc.)
Debido a que la conexión tiene una pequeña ventana de almacenamiento intermedio, si la red se congestiona o el ancho de banda es bajo, el buffer se duplicará si el dispositivo no puede mantener la conexión apropiada.
Cuando se configura con un valor mayor a cero (>0
) el kit de desarrollo de software almacenará esos segundos de audio antes de comenzar la reproducción.
Use SettingsLowDelayKey
con un objeto NSNumber para esta característica. Valores válidos: -1
(modo AUTO), 0
(Desactivado), 2
a 60
segundos.
La función está deshabilitada de forma predeterminada ( 0
).
Ejemplo de demora baja en iOS
NSNumber *delayValue = [NSNumbernumberWithInt:2];
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsLowDelayKey : delayValue,
SettingsMountKey : @"MOBILEFM_AACV2"
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];
Recibir información del historial de reproducción en curso
TDCuePointHistory
se utiliza para acceder a la información de "Historial de reproducción en curso" de los servidores de Triton. Devuelve una lista de CuePointEvents
para un montaje específico. También permite especificar los filtros y limitar la cantidad máxima de elementos devueltos.
@property (strong, nonatomic) TDCuePointHistory *cuePointHistory;
...
NSString *mount = @"MOBILEFM_AACV2";
NSInteger maxItems = 20;
NSArray *filter = @[EventTypeTrack, EventTypeAd];
// Request the history list from the server. The result will be a NSArray of CuePointEvent objects.
[self.cuePointHistory requestHistoryForMount:mount withMaximumItems:maxItems eventTypeFilter:filter completionHandler:^(NSArray *historyItems, NSError *error) {
if (error) {
// Handle the error
}
// Process the cue point list. Ex. display them in a UITableView
self.cuePointList = historyItems;
[self.tableView reloadData];
...
}];
Timeshift
Para obtener más información acerca de Timeshift Radio, consulte la Especificación de streaming.
Para usar Timeshift, debe usar un montaje que esté habilitado para Timeshift.
NSDictionary *settings = @{SettingsStationNameKey : @"BASIC_CONFIG",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : TRITONRADIOMUSICAAC_RW,
SettingsEnableLocationTrackingKey : @(YES),
SettingsTtagKey : @[@"mobile:ios", @"triton:sample"],
StreamParamExtraListenerIdType: @"idfa",
StreamParamExtraListenerIdValue: @"triton-app-id",
};
Función Seek (hacia adelante o hacia atrás):
Agregar o quitar tiempo de la actualPlaybackTime.
Para buscar hacia adelante, use un NSTimeInterval positivo.
Para buscar hacia atrás, use un NSTimeInterval negativo.
[self.tritonPlayer seekToTimeInterval:self.tritonPlayer.currentPlaybackTime - 30.0];
Example:
//Seek forward
self.playerViewController.forwardFiredBlock = ^(UIButton *button) {
[self.tritonPlayer seekToTimeInterval:self.tritonPlayer.currentPlaybackTime + 10.0];
};
Busca vivir:
Para volver a la transmisión en vivo, use seekToLive
. Esto detendrá el stream de Timeshift y se conectará de nuevo al stream en vivo.
[self.tritonPlayer seekToLive]
Obtenga información de Cloud Stream:
Para obtener información sobre el stream en la nube, llame al getCloudStreamInfo
método e implementar el didReceiveCloudStreamInfoEvent
desde TritonPlayerDelegate para recibir la devolución de llamada. Tenga en cuenta que para que esto funcionara, el stream Timeshift tenía que reproducirse. Estamos trabajando en una solución que permita esto en cualquier momento.
self.playerViewController.getCloudStreamInfoFiredBlock = ^(UIButton *button) {
[self.tritonPlayer getCloudStreamInfo];
};
- (void)player:(TritonPlayer *)player didReceiveCloudStreamInfoEvent:(NSDictionary *)cloudStreamInfoEvent {
NSObject *programs = [cloudStreamInfoEvent valueForKey:@"programs"];
if([programs isKindOfClass:[NSDictionary class]]){
NSObject *properties = [(NSDictionary *)programs valueForKey:@"properties"];
NSString *title = [(NSDictionary *)properties valueForKey:@"program_title"];
dispatch_async(dispatch_get_main_queue(), ^{
self.playerViewController.btnTimeshiftProgram.enabled = YES;
self.playerViewController.btnTimeshiftProgram.hidden = NO;
[self.playerViewController.btnTimeshiftProgram setTitle:title forState:UIControlStateNormal];
self.cloudProgramId = [(NSDictionary *)programs valueForKey:@"program_episode_id"];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
self.playerViewController.btnTimeshiftProgram.enabled = NO;
self.playerViewController.btnTimeshiftProgram.hidden = NO;
[self.playerViewController.btnTimeshiftProgram setTitle:@"No Programs" forState:UIControlStateNormal];
});
}
}
Reproducir un programa:
Para reproducir un programa específico, llame al playCloudProgram
que tienen el rol de program_episode_id
como parámetro.
self.playerViewController.timeshiftProgramFiredBlock = ^(UIButton *button) {
[self.tritonPlayer playCloudProgram:self.cloudProgramId];
};
Parámetro Dist
Para utilizar el parámetro dist
con Timeshift necesita agregar ambos parámetros de timeshifting:
SettingsStreamParamsExtraKey : @{StreamParamExtraDist:@"the-dist",
StreamParamExtraDistTimeshift:@"timeshift-dist”}
Los módulos
StreamParamExtraDist:@"the-dist",
El parámetro se utiliza cuando el stream está conectado en modo en vivo .Los módulos
StreamParamExtraDistTimeshift:@"timeshift-dist”,
se utiliza cuando el stream está en modo Timeshift .
El siguiente es un ejemplo de cómo agregar los parámetros:
NSDictionary *settings = @{SettingsStationNameKey : @"MOBILEFM",
SettingsBroadcasterKey : @"Triton Digital",
SettingsMountKey : @"MOBILEFM_AACV2",
SettingsStreamParamsExtraKey : @{
StreamParamExtraDist:@"the-dist",
StreamParamExtraDistTimeshift:@"timeshift-dist"
},
};
self.tritonPlayer = [[TritonPlayer alloc] initWithDelegate:self andSettings:settings];
...
[self.tritonPlayer play];