Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Avviso
Servizi multimediali di Azure verrà ritirato il 30 giugno 2024. Per altre informazioni, vedere la Guida al ritiro di AMS.
In Servizi multimediali di Azure gli eventi live sono responsabili dell'elaborazione di contenuti in streaming live. Un evento live fornisce un endpoint di input (URL di inserimento) che viene quindi fornito a un codificatore live. L'evento live riceve flussi di input dal codificatore live e li rende disponibili per lo streaming tramite uno o più endpoint di streaming. Gli eventi live forniscono anche un endpoint di anteprima (URL di anteprima) usato per visualizzare in anteprima e convalidare il flusso prima di ulteriori elaborazioni e recapito.
Questa esercitazione illustra come usare Node.js e TypeScript per creare un tipo pass-through di un evento live e trasmettere un flusso live a esso usando OBS Studio.
In questa esercitazione si apprenderà come:
- Scaricare il codice di esempio.
- Esaminare il codice che configura ed esegue lo streaming live.
- Guardare l'evento con Azure Media Player nel sito demo di Media Player.
- Pulire le risorse.
Nota
Anche se l'esercitazione usa Node.js esempi, i passaggi generali sono uguali per l'API REST, l'interfaccia della riga di comando o altri SDK supportati.
Prerequisiti
Sono necessari gli elementi seguenti per completare l'esercitazione:
- Installare Node.js.
- Installare TypeScript.
- Creare un account di Servizi multimediali di Azure. Tenere presente i valori usati per il nome del gruppo di risorse e il nome dell'account di Servizi multimediali.
- Seguire la procedura descritta in Accedere all'API servizi multimediali di Azure con l'interfaccia della riga di comando di Azure e salvare le credenziali. Saranno necessari per accedere all'API e configurare il file delle variabili di ambiente.
- Vedere l'articolo Configurare e connettersi con Node.js per comprendere come usare l'SDK client Node.js.
- Installare Visual Studio Code o Visual Studio.
- Configurare l'ambiente di Visual Studio Code per supportare il linguaggio TypeScript.
Sono necessari questi elementi aggiuntivi per il software live-streaming:
Una fotocamera o un dispositivo (ad esempio un portatile) usato per trasmettere un evento.
Codificatore software locale che codifica il flusso della fotocamera e lo invia al servizio live-streaming di Servizi multimediali tramite il Real-Time protocollo RTMP (Messaging Protocol). Per altre informazioni, vedere Codificatori live locali consigliati. Il flusso deve essere in formato RTMP oppure Smooth Streaming.
Questo esempio presuppone che si userà Open Broadcaster Software (OBS) Studio per trasmettere RTMP all'endpoint di inserimento. Installare OBS Studio.
Usare le impostazioni di codifica seguenti in OBS Studio:
- Codificatore: NVIDIA NVENC (se disponibile) o x264
- Controllo frequenza: CBR
- Velocità di bit: 2.500 Kbps (o qualcosa di ragionevole per il computer)
- Intervallo del fotogramma chiave: 2 s o 1 s per bassa latenza
- Set di impostazioni: qualità della latenza bassa o prestazioni (NVENC) o "veryfast" usando x264
- Profilo: alto
- GPU: 0 (auto)
- Max B-frame: 2
Suggerimento
Esaminare Lo streaming live con Servizi multimediali v3 prima di procedere.
Scaricare e configurare l'esempio
Clonare il repository GitHub che contiene l'esempio di Node.js live streaming nel computer usando il comando seguente:
git clone https://github.com/Azure-Samples/media-services-v3-node-tutorials.git
L'esempio di streaming live si trova nella cartella Live .
Nella cartella radice copiare il file denominato sample.env in un nuovo file denominato .env per archiviare le impostazioni delle variabili di ambiente raccolte nell'articolo Accedere all'API di Servizi multimediali di Azure con l'interfaccia della riga di comando di Azure. Assicurarsi che il nome del file includa il punto (.) davanti a "env" in modo che possa funzionare correttamente con l'esempio di codice.
Il file con estensione env contiene la chiave dell'applicazione e il segreto dell'applicazione Azure Active Directory (Azure AD). Contiene anche il nome dell'account e le informazioni sulla sottoscrizione necessarie per autenticare l'accesso SDK all'account di Servizi multimediali. Il file .gitignore è già configurato per impedire la pubblicazione di questo file nel repository forked. Non consentire la perdita di queste credenziali, perché sono importanti segreti per l'account.
Importante
Questo esempio usa un suffisso univoco per ogni risorsa. Se si annulla il debug o si termina l'app senza eseguirla, si finirà con più eventi live nell'account.
Assicurarsi di arrestare gli eventi live in esecuzione. In caso contrario, verrà fatturata! Eseguire automaticamente il programma per il completamento per pulire automaticamente le risorse. Se il programma si arresta o si arresta inavvertitamente il debugger e si interrompe l'esecuzione del programma, è consigliabile controllare il portale per verificare che non siano stati lasciati eventi live nello stato di esecuzione o standby che comportano addebiti di fatturazione indesiderati.
Esaminare il codice TypeScript per lo streaming live
In questa sezione vengono esaminate le funzioni definite nel file index.ts del progetto Live/Standard_Passthrough_Live_Event .
L'esempio crea un suffisso univoco per ogni risorsa in modo che non si verifichino conflitti di nomi se si esegue l'esempio più volte senza effettuare la pulizia.
Iniziare a usare Media Services SDK per Node.js con TypeScript
Per iniziare a usare le API di Servizi multimediali con Node.js, è prima necessario aggiungere il modulo SDK @azure/arm-mediaservices usando la gestione pacchetti npm:
npm install @azure/arm-mediaservices
Nel file package.json , questa operazione è già configurata per l'utente. È sufficiente eseguire npm install per caricare i moduli e le dipendenze:
Installare i pacchetti usati nel file di packages.json :
npm installAprire Visual Studio Code dalla cartella radice. È necessario iniziare dalla cartella in cui si trovano la cartella vscode e i file tsconfig.json .
code .
Aprire la cartella per Live/Standard_Passthrough_Live_Event e aprire il file index.ts nell'editor di Visual Studio Code.
Mentre si è nel file index.ts , selezionare la chiave F5 per aprire il debugger.
Impostazione di longRunningOperationUpdateIntervalMs
Per velocizzare il polling delle operazioni a esecuzione prolungata dall'impostazione predefinita di 30 secondi fino a un paio di secondi, è necessario impostare longRunningOperationUpdateIntervalMs e passare questo valore alla proprietà updateIntervaleInMs del parametro opzioni sulle operazioni createAndWait() quando si usano liveEvents. Questo può essere visto in tutto l'esempio. Questo esempio usa un valore pari a 2000 ms (2 secondi). Questa modifica riduce il tempo necessario per eseguire il polling dello stato di un'operazione a esecuzione prolungata nell'endpoint di Resource Manager di Azure. Ridurrà il tempo per completare operazioni principali come la creazione di eventi live, l'avvio e l'arresto, che sono tutte chiamate asincrone. È consigliabile un valore di 2 secondi per la maggior parte degli scenari sensibili al tempo.
// Long running operation polling interval in milliseconds
const longRunningOperationUpdateIntervalMs = 2000;
Creare un evento live
Questa sezione illustra come creare un tipo pass-through standard di evento live (LiveEventEncodingType impostato su PassthroughStandard). Per informazioni sui tipi disponibili, vedere Tipi di eventi live. Oltre a pass-through basic o standard, è possibile usare un evento di codifica live per 720p o 1080p di codifica cloud a bitrate adattivo.
Alcuni esempi di questi tipi di eventi sono disponibili nella cartella Live del repository di esempio. Inoltre, un esempio che illustra come ascoltare gli eventi di Griglia di eventi tramite Hub eventi è incluso anche.
È possibile specificare gli elementi seguenti quando si crea l'evento live:
Protocollo di inserimento per l'evento live. Attualmente sono supportati i protocolli RTMP, RTMPS e Smooth Streaming. Non è possibile modificare l'opzione del protocollo mentre l'evento live o i relativi output live associati sono in esecuzione. Se sono necessari protocolli diversi, creare un evento live separato per ogni protocollo di streaming.
Restrizioni IP per l'inserimento e l'anteprima. È possibile definire gli indirizzi IP consentiti per inserire un video in questo evento live. Gli indirizzi IP consentiti possono essere specificati come una di queste opzioni:
- Un singolo indirizzo IP (ad esempio,
10.0.0.1) - Intervallo IP che usa un indirizzo IP e una subnet di Inter-Domain routing senza classi (CIDR) (ad esempio,
10.0.0.1/22) - Intervallo IP che usa un indirizzo IP e una subnet mask decimale punteggiata (ad esempio,
10.0.0.1(255.255.252.0))
Se non viene specificato alcun indirizzo IP e non è presente una definizione della regola, non sarà consentito alcun indirizzo IP. Per consentire qualsiasi indirizzo IP, creare una regola e impostare
0.0.0.0/0. Gli indirizzi IP devono trovarsi in uno dei formati seguenti: indirizzi IPv4 o IPv6 con quattro numeri o un intervallo di indirizzi CIDR. Per altre informazioni sull'uso di IPv4 o IPv6, vedere Limitare l'accesso alla licenza DRM e al recapito delle chiavi AES usando gli elenchi di indirizzi IP consentiti.- Un singolo indirizzo IP (ad esempio,
Avvio automatico in un evento durante la creazione. Quando l'avvio automatico è impostato su
true, l'evento live inizierà dopo la creazione. Ciò significa che la fatturazione viene avviata non appena viene avviato l'evento live. È necessario chiamareStopin modo esplicito la risorsa evento live per arrestare ulteriormente la fatturazione. Per altre informazioni, vedere Stati eventi live e fatturazione.Le modalità standby sono disponibili per avviare l'evento live in uno stato "allocato" a costo inferiore che rende più veloce passare a uno stato in esecuzione. Ciò è utile per situazioni come pool di accesso frequente che devono distribuire rapidamente i canali ai streamer.
Nome host statico e GUID univoco. Per un URL di inserimento che sia predittivo e più semplice da gestire in un codificatore live basato su hardware, impostare la
useStaticHostnameproprietà sutrue. PeraccessToken, usare un GUID personalizzato e univoco. Per informazioni dettagliate, vedere URL di inserimento eventi live.
// Creating the LiveEvent - the primary object for live streaming in AMS.
// See the overview - https://docs.microsoft.com/azure/media-services/latest/live-streaming-overview
// Create the LiveEvent
// Understand the concepts of what a live event and a live output is in AMS first!
// Read the following - https://docs.microsoft.com/azure/media-services/latest/live-events-outputs-concept
// 1) Understand the billing implications for the various states
// 2) Understand the different live event types, pass-through and encoding
// 3) Understand how to use long-running async operations
// 4) Understand the available Standby mode and how it differs from the Running Mode.
// 5) Understand the differences between a LiveOutput and the Asset that it records to. They are two different concepts.
// A live output can be considered as the "tape recorder" and the Asset is the tape that is inserted into it for recording.
// 6) Understand the advanced options such as low latency, and live transcription/captioning support.
// Live Transcription - https://docs.microsoft.com/en-us/azure/media-services/latest/live-transcription
// Low Latency - https://docs.microsoft.com/en-us/azure/media-services/latest/live-event-latency
// When broadcasting to a live event, please use one of the verified on-premises live streaming encoders.
// While operating this tutorial, it is recommended to start out using OBS Studio before moving to another encoder.
// Note: When creating a LiveEvent, you can specify allowed IP addresses in one of the following formats:
// To allow all IPv4 addresses and block all IPv6 addresses, set the IP allow list to [ "0.0.0.0/0" ]
// IpV4 address with 4 numbers
// CIDR address range
let allowAllIPv4InputRange: IPRange = {
name: "Allow all IPv4 addresses",
address: "0.0.0.0",
subnetPrefixLength: 0
};
// IpV6 addresses or ranges
// For this example, the following request from the following addresses will be accepted:
// • IPv6 addresses between 2001:1234:1234:0000:0000:0000:0000:4567 and 2001:1234:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF,
// • IPv6 address 2001:1235:0000:0000:0000:0000:0000:0000
// Additional examples:
// • To allow requests from any IP address, set the “defaultAction” of the “accessControl” block to “Allow” (and do not specify an “ipAllowList)
// • To allow all IPv6 addresses and block all IPv6 addresses, set the IP allow list to [ "::/0" ]
let allowAllIPv6InputRange: IPRange = {
name: "Allow all IPv6 addresses",
address: "::",
subnetPrefixLength: 0
};
// Create the LiveEvent input IP access control object
// this will control the IP that the encoder is running on and restrict access to only that encoder IP range.
let liveEventInputAccess: LiveEventInputAccessControl = {
ip: {
allow: [
// re-use the same range here for the sample, but in production you can lock this
// down to the ip range for your on-premises live encoder, laptop, or device that is sending
// the live stream
allowAllIPv4InputRange,
allowAllIPv6InputRange
]
}
};
// Create the LiveEvent Preview IP access control object.
// This will restrict which clients can view the preview endpoint
let liveEventPreview: LiveEventPreview = {
accessControl: {
ip: {
allow: [
// re-use the same range here for the sample, but in production you can lock this to the IPs of your
// devices that would be monitoring the live preview.
allowAllIPv4InputRange,
allowAllIPv6InputRange
]
}
}
}
// To get the same ingest URL for the same LiveEvent name every single time...
// 1. Set useStaticHostname to true so you have ingest like:
// rtmps://liveevent-hevc12-eventgridmediaservice-usw22.channel.media.azure.net:2935/live/522f9b27dd2d4b26aeb9ef8ab96c5c77
// 2. Set accessToken to a desired GUID string (with or without hyphen)
// See REST API documentation for details on each setting value
// https://docs.microsoft.com/rest/api/media/liveevents/create
let liveEventCreate: LiveEvent = {
location: mediaAccount.location,
description: "Sample Live Event from Node.js SDK sample",
// Set useStaticHostname to true to make the ingest and preview URL host name the same.
// This can slow things down a bit.
useStaticHostname: true,
//hostnamePrefix: "somethingstatic", /// When using Static host name true, you can control the host prefix name here if desired
// 1) Set up the input settings for the Live event...
input: {
streamingProtocol: KnownLiveEventInputProtocol.Rtmp, // options are RTMP or Smooth Streaming ingest format.
accessControl: liveEventInputAccess, // controls the IP restriction for the source encoder.
// keyFrameIntervalDuration: "PT2S", // Set this to match the ingest encoder's settings. This should not be used for encoding live events
accessToken: "9eb1f703b149417c8448771867f48501" // Use this value when you want to make sure the ingest URL is static and always the same. If omitted, the service will generate a random GUID value.
},
// 2) Set the live event to use pass-through or cloud encoding modes...
encoding: {
// Set this to Basic pass-through, Standard pass-through, Standard or Premium1080P to use the cloud live encoder.
// See https://go.microsoft.com/fwlink/?linkid=2095101 for more information
// Otherwise, leave as "None" to use pass-through mode
encodingType: KnownLiveEventEncodingType.PassthroughStandard,
// OPTIONS for encoding type you can use:
// encodingType: KnownLiveEventEncodingType.PassthroughBasic, // Basic pass-through mode - the cheapest option!
// encodingType: KnownLiveEventEncodingType.PassthroughStandard, // also known as standard pass-through mode (formerly "none")
// encodingType: KnownLiveEventEncodingType.Premium1080p,// live transcoding up to 1080P 30fps with adaptive bitrate set
// encodingType: KnownLiveEventEncodingType.Standard,// use live transcoding in the cloud for 720P 30fps with adaptive bitrate set
//
// OPTIONS using live cloud encoding type:
// keyFrameInterval: "PT2S", //If this value is not set for an encoding live event, the fragment duration defaults to 2 seconds. The value cannot be set for pass-through live events.
// presetName: null, // only used for custom defined presets.
//stretchMode: KnownStretchMode.None // can be used to determine stretch on encoder mode
},
// 3) Set up the Preview endpoint for monitoring based on the settings above we already set.
preview: liveEventPreview,
// 4) Set up more advanced options on the live event. Low Latency is the most common one.
streamOptions: [
"LowLatency"
],
// 5) Optionally enable live transcriptions if desired.
// WARNING : This is extra cost ($$$), so please check pricing before enabling. Transcriptions are not supported on PassthroughBasic.
// switch this sample to use encodingType: "PassthroughStandard" first before un-commenting the transcriptions object below.
/* transcriptions : [
{
inputTrackSelection: [], // chose which track to transcribe on the source input.
// The value should be in BCP-47 format (e.g: 'en-US'). See https://go.microsoft.com/fwlink/?linkid=2133742
language: "en-us",
outputTranscriptionTrack: {
trackName : "English" // set the name you want to appear in the output manifest
}
}
]
*/
}
console.log("Creating the LiveEvent, please be patient as this can take time to complete async.")
console.log("Live Event creation is an async operation in Azure and timing can depend on resources available.")
console.log();
let timeStart = process.hrtime();
// When autostart is set to true, the Live Event will be started after creation.
// That means, the billing starts as soon as the Live Event starts running.
// You must explicitly call Stop on the Live Event resource to halt further billing.
// The following operation can sometimes take awhile. Be patient.
// On optional workflow is to first call allocate() instead of create.
// https://docs.microsoft.com/en-us/rest/api/media/liveevents/allocate
// This allows you to allocate the resources and place the live event into a "Standby" mode until
// you are ready to transition to "Running". This is useful when you want to pool resources in a warm "Standby" state at a reduced cost.
// The transition from Standby to "Running" is much faster than cold creation to "Running" using the autostart property.
// Returns a long running operation polling object that can be used to poll until completion.
await mediaServicesClient.liveEvents.beginCreateAndWait(
resourceGroup,
accountName,
liveEventName,
liveEventCreate,
// When autostart is set to true, you should "await" this method operation to complete.
// The Live Event will be started after creation.
// You may choose not to do this, but create the object, and then start it using the standby state to
// keep the resources "warm" and billing at a lower cost until you are ready to go live.
// That increases the speed of startup when you are ready to go live.
{
autoStart: false,
updateIntervalInMs: longRunningOperationUpdateIntervalMs // This sets the polling interval for the long running ARM operation (LRO)
}
).then((liveEvent) => {
let timeEnd = process.hrtime(timeStart);
console.info(`Live Event Created - long running operation complete! Name: ${liveEvent.name}`)
console.info(`Execution time for create LiveEvent: %ds %dms`, timeEnd[0], timeEnd[1] / 1000000);
console.log();
}).catch((reason) => {
if (reason.error && reason.error.message) {
console.info(`Live Event creation failed: ${reason.message}`);
}
})
Creare un asset per registrare e archiviare l'evento live
Nel blocco di codice seguente si crea un asset vuoto da usare come "nastro" per registrare l'archivio eventi live.
Quando si imparano questi concetti, è utile pensare all'oggetto asset come nastro che si inserisce in un registratore video nei vecchi giorni. L'output live è la macchina registratore nastro. L'evento live è solo il segnale video che entra nella parte posteriore della macchina.
Tenere presente che l'asset, o "nastro", può essere creato in qualsiasi momento. L'asset vuoto verrà mano all'oggetto di output live, il "registratore nastro" in questa analogia.
// Create an Asset for the LiveOutput to use. Think of this as the "tape" that will be recorded to.
// The asset entity points to a folder/container in your Azure Storage account.
console.log(`Creating an asset named: ${assetName}`);
console.log();
let asset = await mediaServicesClient.assets.createOrUpdate(resourceGroup, accountName, assetName, {});
// Create the Live Output - think of this as the "tape recorder for the live event".
// Live outputs are optional, but are required if you want to archive the event to storage,
// use the asset for on-demand playback later, or if you want to enable cloud DVR time-shifting.
// We will use the asset created above for the "tape" to record to.
let manifestName: string = "output";
console.log(`Creating a live output named: ${liveOutputName}`);
console.log();
// See the REST API for details on each of the settings on Live Output
// https://docs.microsoft.com/rest/api/media/liveoutputs/create
Creare l'output live
In questa sezione viene creato un output live che usa il nome dell'asset come input per indicare a dove registrare l'evento live. Inoltre, è stata configurata la finestra DVR (Time Shift) da usare nella registrazione.
Il codice di esempio illustra come configurare una finestra di spostamento orario di 1 ora. Questa finestra consente ai client di riprodurre qualsiasi elemento nell'ultima ora dell'evento. Inoltre, solo l'ultima ora dell'evento live rimarrà nell'archivio. È possibile estendere questa finestra fino a 25 ore, se necessario. Si noti anche che è possibile controllare la denominazione del manifesto di output che i manifesti HTTP Live Streaming (HLS) e Dynamic Adaptive Streaming over HTTP (DASH) usano nei percorsi URL durante la pubblicazione.
L'output live, o "registratore nastro" nella nostra analogia, può essere creato anche in qualsiasi momento. È possibile creare un output live prima di avviare il flusso di segnale o dopo. Se è necessario velocizzare le operazioni, è spesso utile creare l'output prima di avviare il flusso di segnale.
Gli output live iniziano quando vengono creati e arrestati quando vengono eliminati. Quando si elimina l'output live, non si elimina l'asset o il contenuto sottostante nell'asset. Consideralo come esettare il "nastro". L'asset con la registrazione dura fino a quando ti piace. Quando viene espulsa (ovvero, quando l'output live viene eliminato), sarà disponibile per la visualizzazione su richiesta immediatamente.
let liveOutputCreate: LiveOutput;
if (asset.name) {
liveOutputCreate = {
description: "Optional description when using more than one live output",
assetName: asset.name,
manifestName: manifestName, // The HLS and DASH manifest file name. This is recommended to set if you want a deterministic manifest path up front.
archiveWindowLength: "PT30M", // sets the asset archive window to 30 minutes. Uses ISO 8601 format string.
rewindWindowLength: "PT30M", // sets the time-shit(DVR) window to 30 minutes. Uses ISO 8601 format string.
hls: {
fragmentsPerTsSegment: 1 // Advanced setting when using HLS TS output only.
},
}
// Create and await the live output
await mediaServicesClient.liveOutputs.beginCreateAndWait(
resourceGroup,
accountName,
liveEventName,
liveOutputName,
liveOutputCreate,
{
updateIntervalInMs: longRunningOperationUpdateIntervalMs // Setting this adjusts the polling interval of the long running operation.
})
.then((liveOutput) => {
console.log(`Live Output Created: ${liveOutput.name}`);
let timeEnd = process.hrtime(timeStart);
console.info(`Execution time for create Live Output: %ds %dms`, timeEnd[0], timeEnd[1] / 1000000);
console.log();
})
.catch((reason) => {
if (reason.error && reason.error.message) {
console.info(`Live Output creation failed: ${reason.message}`);
}
});
}
Ottenere gli URL di inserimento
Dopo aver creato l'evento live, è possibile ottenere GLI URL di inserimento forniti al codificatore live. Il codificatore usa questi URL per inserire un flusso live usando il protocollo RTMP.
// Get the RTMP ingest URL to configure in OBS Studio.
// The endpoints is a collection of RTMP primary and secondary, and RTMPS primary and secondary URLs.
// to get the primary secure RTMPS, it is usually going to be index 3, but you could add a loop here to confirm...
if (liveEvent.input?.endpoints) {
let ingestUrl = liveEvent.input.endpoints[0].url;
console.log(`The RTMP ingest URL to enter into OBS Studio is:`);
console.log(`RTMP ingest : ${ingestUrl}`);
console.log(`Make sure to enter a Stream Key into the OBS studio settings. It can be any value or you can repeat the accessToken used in the ingest URL path.`);
console.log();
}
Ottenere l'URL di anteprima
Usare previewEndpoint per visualizzare in anteprima e verificare che l'input del codificatore venga ricevuto.
Importante
Assicurarsi che il video sia in flusso all'URL di anteprima prima di continuare.
if (liveEvent.preview?.endpoints) {
// Use the previewEndpoint to preview and verify
// that the input from the encoder is actually being received
// The preview endpoint URL also support the addition of various format strings for HLS (format=m3u8-cmaf) and DASH (format=mpd-time-cmaf) for example.
// The default manifest is Smooth.
let previewEndpoint = liveEvent.preview.endpoints[0].url;
console.log("The preview url is:");
console.log(previewEndpoint);
console.log();
console.log("Open the live preview in your browser and use any DASH or HLS player to monitor the preview playback:");
console.log(`https://ampdemo.azureedge.net/?url=${previewEndpoint}(format=mpd-time-cmaf)&heuristicprofile=lowlatency`);
console.log("You will need to refresh the player page SEVERAL times until enough data has arrived to allow for manifest creation.");
console.log("In a production player, the player can inspect the manifest to see if it contains enough content for the player to load and auto reload.");
console.log();
}
console.log("Start the live stream now, sending the input to the ingest url and verify that it is arriving with the preview url.");
console.log("IMPORTANT TIP!: Make CERTAIN that the video is flowing to the Preview URL before continuing!");
Creare e gestire eventi live e output live
Dopo aver eseguito il flusso nell'evento live, è possibile iniziare l'evento di streaming pubblicando un localizzatore di streaming per i giocatori client da usare. In questo modo verrà reso disponibile per gli spettatori tramite l'endpoint di streaming.
Creare prima il segnale creando l'evento live. Il segnale non scorre fino a quando non si avvia l'evento live e si connette il codificatore all'input.
Per arrestare il "registratore nastro", si chiama delete su LiveOutput. Questa azione non elimina il contenuto dell'archivio sul "nastro" (asset). Elimina solo "registratore nastro" e arresta l'archiviazione. L'asset viene sempre mantenuto con il contenuto video archiviato fino a quando non si chiama delete in modo esplicito sull'asset stesso. Non appena si elimina LiveOutput, il contenuto registrato dell'asset è ancora disponibile per riprodurre tramite gli URL del localizzatore di streaming pubblicati.
Se si vuole rimuovere la possibilità di un client di riprodurre il contenuto archiviato, è prima necessario rimuovere tutti i localizzatori dall'asset. Si scarica anche la cache della rete di distribuzione del contenuto (RETE CDN) nel percorso URL, se si usa una rete CDN per il recapito. In caso contrario, il contenuto verrà vissuto nella cache della rete CDN per l'impostazione tempo-live standard sulla rete CDN (che potrebbe essere fino a 72 ore).
Creare un localizzatore di streaming per pubblicare manifesti HLS e DASH
Nota
Quando l'account di Servizi multimediali viene creato, un endpoint di streaming predefinito viene aggiunto all'account nello stato arrestato. Per avviare lo streaming del contenuto e sfruttare il pacchetto dinamico e la crittografia dinamica, l'endpoint di streaming da cui si vuole trasmettere il contenuto deve trovarsi nello stato in esecuzione.
Quando si pubblica l'asset usando un localizzatore di streaming, l'evento live (fino alla lunghezza della finestra DVR) continuerà a essere visualizzabile fino alla scadenza o all'eliminazione del localizzatore di streaming. Questo è il modo in cui si rende disponibile la registrazione virtuale "nastro" per il pubblico di visualizzazione per visualizzare live e su richiesta. Lo stesso URL può essere usato per watch l'evento live, la finestra DVR o l'asset su richiesta al termine della registrazione (quando l'output live viene eliminato).
async function createStreamingLocator(assetName: string, locatorName: string) {
let streamingLocator = {
assetName: assetName,
streamingPolicyName: "Predefined_ClearStreamingOnly" // no DRM or AES128 encryption protection on this asset. Clear means un-encrypted.
};
let locator = await mediaServicesClient.streamingLocators.create(
resourceGroup,
accountName,
locatorName,
streamingLocator);
return locator;
}
Creare i percorsi dei manifesti HLS e DASH
Il metodo BuildManifestPaths nell'esempio illustra come creare in modo deterministico i percorsi di streaming da usare per il recapito di HLS o DASH a vari client e framework del lettore.
// This method builds the manifest URL from the static values used during creation of the Live Output.
// This allows you to have a deterministic manifest path. <streaming endpoint hostname>/<streaming locator ID>/manifestName.ism/manifest(<format string>)
async function buildManifestPaths(scheme: string, hostname: string | undefined, streamingLocatorId: string | undefined, manifestName: string) {
const hlsFormat: string = "format=m3u8-cmaf";
const dashFormat: string = "format=mpd-time-cmaf";
let manifestBase = `${scheme}://${hostname}/${streamingLocatorId}/${manifestName}.ism/manifest`
let hlsManifest = `${manifestBase}(${hlsFormat})`;
console.log(`The HLS (MP4) manifest URL is : ${hlsManifest}`);
console.log("Open the following URL to playback the live stream in an HLS compliant player (HLS.js, Shaka, ExoPlayer) or directly in an iOS device");
console.log(`${hlsManifest}`);
console.log();
let dashManifest = `${manifestBase}(${dashFormat})`;
console.log(`The DASH manifest URL is : ${dashManifest}`);
console.log("Open the following URL to playback the live stream from the LiveOutput in the Azure Media Player");
console.log(`https://ampdemo.azureedge.net/?url=${dashManifest}&heuristicprofile=lowlatency`);
console.log();
}
Guardare l'evento
Per watch l'evento, copiare l'URL di streaming ottenuto quando è stato eseguito il codice per creare un localizzatore di streaming. È possibile usare il lettore multimediale desiderato. Azure Media Player è disponibile per testare il flusso nel sito demo di Media Player.
Un evento live converte automaticamente gli eventi nel contenuto on demand quando viene arrestato. Anche dopo l'arresto e l'eliminazione dell'evento, gli utenti potranno riprodurre in streaming il contenuto archiviato sotto forma di video on demand, fintanto che l'asset non viene eliminato. Non è possibile eliminare un asset se un evento lo usa; l'evento deve essere eliminato prima.
Pulire le risorse nell'account di Servizi multimediali
Se si esegue l'applicazione in tutto il modo, verrà pulita automaticamente tutte le risorse usate nella cleanUpResources funzione. Assicurarsi che l'applicazione o il debugger venga eseguito tutto il modo per il completamento oppure si potrebbero perdere risorse e terminare con l'esecuzione di eventi live nell'account. Eseguire il doppio controllo nella portale di Azure per verificare che tutte le risorse vengano pulite nell'account di Servizi multimediali.
Nel codice di esempio fare riferimento al cleanUpResources metodo per informazioni dettagliate.
Importante
L'uscita dell'evento live in esecuzione comporta costi di fatturazione. Tenere presente che se il progetto o il programma non risponde o viene chiuso per qualsiasi motivo, potrebbe lasciare l'evento live in esecuzione in uno stato di fatturazione.
Porre domande, fornire feedback, ottenere aggiornamenti
Consultare l'articolo Community di Servizi multimediali di Azure per esaminare i diversi modi in cui è possibile porre domande, fornire feedback e ottenere aggiornamenti su Servizi multimediali.
Altre documentazioni per sviluppatori per Node.js in Azure
- Azure per sviluppatori JavaScript e Node.js
- Media Services source code in the @azure/azure-sdk-for-js GitHub repo
- Documentazione del pacchetto di Azure per gli sviluppatori di Node.js
Guida e supporto tecnico
È possibile contattare Servizi multimediali con domande o seguire gli aggiornamenti in base a uno dei metodi seguenti:
- DOMANDE E RISPOSTE
-
Stack Overflow. Contrassegna le domande con
azure-media-services. - @MSFTAzureMedia o usare @AzureSupport per richiedere supporto.
- Aprire un ticket di supporto tramite il portale di Azure.