This document identifies the different types of errors that YouTube Live Streaming API operations can return. You can also find a list of errors for any individual method in the reference documentation for that method.
fanFundingEvents
The following tables identify error messages that the API returns in response to calls related to fanFundingEvents
resources.
fanFundingEvents.list
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
insufficientPermissions |
You do not have the necessary permissions to view the channel’s Fan Funding events. |
invalidValue (400) |
fanFundingNotEnabledForChannelId |
The channel does not have Fan Funding enabled. |
liveBroadcasts
The following tables identify error messages that the API returns in response to calls related to liveBroadcasts
resources.
liveBroadcasts.bind
Error type | Error detail | Description |
---|---|---|
backendError |
internalError |
An internal error occurred during the bind. |
forbidden (403) |
liveBroadcastBindingNotAllowed |
The current status of the live broadcast does not allow it to be bound to a stream. |
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to retrieve the specified live broadcast. For more information, see Implementing OAuth2 authentication. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
notFound (404) |
liveBroadcastNotFound |
The broadcast specified by the id parameter does not exist. |
notFound (404) |
liveStreamNotFound |
The stream specified by the streamId parameter does not exist. |
rateLimitExceeded |
userRequestsExceedRateLimit |
The user has sent too many requests in a given timeframe. |
required (400) |
idRequired |
The required id parameter must identify the broadcast to bind. |
liveBroadcasts.delete
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
liveBroadcastDeletionNotAllowed |
The current status of the live broadcast does not allow it to be deleted. |
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to delete the specified live broadcast. For more information, see Implementing OAuth2 authentication. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
notFound (404) |
liveBroadcastNotFound |
The id property specified in the liveBroadcast resource did not identify a broadcast. |
liveBroadcasts.insert
Error type | Error detail | Description |
---|---|---|
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to create the live broadcast. |
insufficientPermissions |
livePermissionBlocked |
The user that authorized the request is unable to stream live video on YouTube at this time. Details explaining why the user cannot stream live video may be available in the user’s channel settings at https://www.youtube.com/features. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
invalidValue (400) |
invalidAutoStart |
The liveBroadcast resource contained an invalid value for the contentDetails.enableAutoStart property.Not all broadcasts support this setting. |
invalidValue (400) |
invalidAutoStop |
The liveBroadcast resource contained an invalid value for the contentDetails.enableAutoStop property. Youcannot modify the enableAutoStop setting for a persistent broadcast. |
invalidValue (400) |
invalidDescription |
The liveBroadcast resource did not specify a valid value for the snippet.description property. The property’s value can contain up to 5000 characters. |
invalidValue (400) |
invalidEmbedSetting |
The liveBroadcast resource contained an invalid value for the contentDetails.enable_embed property. You cannot embed this broadcast. |
invalidValue (400) |
invalidLatencyPreferenceOptions |
The liveBroadcast resource contained an invalid value for the contentDetails.latencyPreference property.Not all settings are supported with this latency preference. |
invalidValue (400) |
invalidPrivacyStatus |
The liveBroadcast resource contained an invalid value for the status.privacy_status property. |
invalidValue (400) |
invalidProjection |
The liveBroadcast resource contained an invalid value for the contentDetails.projection property. A default broadcast’s projection cannot be set to 360 . |
invalidValue (400) |
invalidScheduledEndTime |
The liveBroadcast resource contained an invalid value for the snippet.scheduledEndTime property. The scheduled end time must follow the scheduled start time. |
invalidValue (400) |
invalidScheduledStartTime |
The liveBroadcast resource contained an invalid value for the snippet.scheduledStartTime property. The scheduled start time must be in the future and close enough to the current date that a broadcast could be reliably scheduled at that time. |
invalidValue (400) |
invalidTitle |
The liveBroadcast resource did not specify a valid value for the snippet.title property. The property’s value must be between 1 and 100 characters long. |
limitExceeded |
userBroadcastsExceedLimit |
The user has created too many live or scheduled broadcasts and must stop or delete some. |
rateLimitExceeded |
userRequestsExceedRateLimit |
The user has sent too many requests in a given timeframe. |
required (400) |
privacyStatusRequired |
The liveBroadcast resource must specify a privacy status. See valid privacyStatus values. |
required (400) |
scheduledEndTimeRequired |
The liveBroadcast resource must specify the snippet.scheduledEndTime property. |
required (400) |
scheduledStartTimeRequired |
The liveBroadcast resource must specify the snippet.scheduledStartTime property. |
required (400) |
titleRequired |
The liveBroadcast resource must specify the snippet.title property. |
liveBroadcasts.list
Error type | Error detail | Description |
---|---|---|
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to retrieve the live broadcast. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
liveBroadcasts.transition
Error type | Error detail | Description |
---|---|---|
backendError |
errorExecutingTransition |
An error occurred while changing the broadcast’s status. |
forbidden (403) |
errorStreamInactive |
The requested transition is not allowed when the stream that is bound to the broadcast is inactive. |
forbidden (403) |
invalidTransition |
The live broadcast can’t transition from its current status to the requested status. |
forbidden (403) |
redundantTransition |
The live broadcast is already in the requested status or processing to the requested status. |
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to transition the live broadcast. |
insufficientPermissions |
livePermissionBlocked |
The user that authorized the request is unable to stream live video on YouTube at this time. Details explaining why the user cannot stream live video may be available in the user’s channel settings at https://www.youtube.com/features. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
notFound (404) |
liveBroadcastNotFound |
The broadcast specified by the id parameter does not exist. |
rateLimitExceeded (403) |
userRequestsExceedRateLimit |
The user has sent too many requests in a given timeframe. |
required (400) |
idRequired |
The required id parameter must identify the broadcast whose status you want to transition. |
required (400) |
statusRequired |
The API request must specify a value for the status parameter. |
liveBroadcasts.update
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
closedCaptionsTypeModificationNotAllowed |
The contentDetails.closedCaptionsType value can only be modified when the broadcast is in the created or ready status. |
forbidden (403) |
enableAutoStartModificationNotAllowed |
The contentDetails.enableAutoStart value can only be modified when the stream is inactive and the broadcast is in the created or ready status. |
forbidden (403) |
enableClosedCaptionsModificationNotAllowed |
The contentDetails.enableClosedCaptions value can only be modified when the broadcast’s status is created or ready . |
forbidden (403) |
enableDvrModificationNotAllowed |
The contentDetails.enableDvr value can be modified only when the broadcast’s status is created or ready . |
forbidden (403) |
enableMonitorStreamModificationNotAllowed |
The contentDetails.monitorStream.enableMonitorStream value can be modified only when the broadcast’s status is created or ready . |
forbidden (403) |
recordFromStartModificationNotAllowed |
The contentDetails.recordFromStart value can be modified only when the broadcast’s status is created or ready . |
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to update the specified live broadcast. For more information, see Implementing OAuth2 authentication. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
invalidValue (400) |
invalidAutoStart |
The liveBroadcast resource contained an invalid value for the contentDetails.enableAutoStart property.You cannot modify the enableAutoStart setting for a persistent broadcast. |
invalidValue (400) |
invalidAutoStop |
The liveBroadcast resource contained an invalid value for the contentDetails.enableAutoStop property. Youcannot modify the enableAutoStop setting for a persistent broadcast. |
invalidValue (400) |
invalidDescription |
The liveBroadcast resource did not specify a valid value for the snippet.description property. snippet.description can contain up to 5000 characters. |
invalidValue (400) |
invalidEmbedSetting |
The liveBroadcast resource contained an invalid value for the contentDetails.enable_embed property. You cannot embed this broadcast. |
invalidValue (400) |
invalidEnableClosedCaptions |
In the liveBroadcast resource, the value of the contentDetails.enableClosedCaptions property is incompatible with the value of the contentDetails.closedCaptionType setting. Modify the resource to only include one of the two properties, and then resubmit the request. |
invalidValue (400) |
invalidLatencyPreferenceOptions |
The liveBroadcast resource contained an invalid value for the contentDetails.latencyPreference property.Not all settings are supported with this latency preference. |
invalidValue (400) |
invalidPrivacyStatus |
The liveBroadcast resource did not specify a valid privacy status. See valid privacyStatus values. |
invalidValue (400) |
invalidProjection |
The liveBroadcast resource contained an invalid value for the contentDetails.projection property. A persistent broadcast’s projection cannot be set to 360. |
invalidValue (400) |
invalidScheduledEndTime |
The liveBroadcast resource contained an invalid value for the snippet.scheduledEndTime property. The scheduled end time must follow the scheduled start time. |
invalidValue (400) |
invalidScheduledStartTime |
The liveBroadcast resource contained an invalid value for the snippet.scheduledStartTime property. The scheduled start time must be in the future. |
invalidValue (400) |
invalidTitle |
The liveBroadcast resource did not specify a valid value for the snippet.title property. snippet.title must be between 1 and 100 characters long. |
notFound (404) |
liveBroadcastNotFound |
The id property specified in the liveBroadcast resource did not identify a broadcast. |
required (400) |
broadcastStreamDelayMsRequired |
The liveBroadcast resource did not specify the contentDetails.monitorStream.broadcastStreamDelayMs property. |
required (400) |
enableMonitorStreamRequired |
The liveBroadcast resource did not specify the contentDetails.monitorStream.enableMonitorStream property. |
required (400) |
idRequired |
The liveBroadcast resource must include and specify a value for the id property. |
required (400) |
privacyStatusRequired |
The liveBroadcast resource did not specify a privacy status. See for valid privacyStatus values. |
required (400) |
scheduledEndTimeRequired |
The liveBroadcast resource did not specify the snippet.scheduledEndTime property. |
required (400) |
scheduledStartTimeRequired |
The liveBroadcast resource did not specify the snippet.scheduledStartTime property. |
required (400) |
titleRequired |
The liveBroadcast resource did not specify the snippet.title property. |
liveBroadcasts.cuepoint
Error type | Error detail | Description |
---|---|---|
insufficientPermissions (403) |
insufficientLivePermissions |
The request is not authorized to insert a cuepoint in the live broadcast. |
insufficientPermissions (403) |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://support.google.com/youtube/answer/2474026 and https://www.youtube.com/features. |
rateLimitExceeded (403) |
userRequestsExceedRateLimit |
The user has sent too many requests in a given timeframe. |
required (400) |
idRequired |
The required id parameter must identify the broadcastin which you want to insert a cuepoint. |
required (400) |
cueTypeRequired |
The required cueType field must be specified in theAPI request body. |
notFound (404) |
liveBroadcastNotFound |
The broadcast specified by the id parameter does not exist. |
invalidValue (400) |
conflictingTimeFields |
Only one of insertionOffsetTimeMs andwalltimeMs may be specified. Setting both values causes an error. If you donot set either value, YouTube will use the default insertionOffsetTimeMs time( 0 ), which means that the cuepoint will be inserted as soon as possible. |
invalidValue (400) |
invalidInsertionOffsetTimeMs |
The cuepoint resource specified an invalid value for theinsertionOffsetTimeMs property. The value must be 0 or a positiveinteger. |
invalidValue (400) |
invalidWalltimeMs |
The cuepoint resource specified an invalid value for thewalltimeMs property. The value must be an integer that represents an epochtimestamp. |
backendError (5xx) |
serviceUnavailable |
The service is unavailable. Try your request again after a few minutes. |
liveChatBans
The following tables identify error messages that the API returns in response to calls related to liveChatBans
resources.
liveChatBans.delete
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
forbidden |
The specified ban cannot be removed. This error can occur if the request is authorized by one moderator who is attempting to remove a ban on another moderator. |
forbidden (403) |
insufficientPermissions |
You do not have the necessary permissions to remove the specified ban. |
invalidValue (400) |
invalidLiveChatBanId |
The id parameter specifies an invalid value. |
notFound (404) |
liveChatBanNotFound |
The specified ban cannot be found. |
liveChatBans.insert
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
insufficientPermissions |
You do not have the necessary permissions to ban a user from the specified live chat. |
forbidden (403) |
liveChatBanInsertionNotAllowed |
The specified ban cannot be created. This error can occur if the request attempts to ban the chat owner or another moderator. |
invalidValue (400) |
invalidChannelId |
The specified channel ID cannot be found. |
invalidValue (400) |
invalidLiveChatId |
The snippet.liveChatId value specified in the request is invalid. Check the associated liveBroadcast resource to ensure that you have the correct value. |
notFound (404) |
liveChatNotFound |
The specified live chat cannot be found. Check the associated liveBroadcast resource to ensure that you are setting the snippet.liveChatId property to the correct value. |
notFound (404) |
liveChatUserNotFound |
The live chat user you are trying to ban cannot be found. |
required (400) |
bannedUserChannelIdRequired |
The liveChatBan resource submitted in the request body must specify a value for the snippet.bannedUserDetails.channelId property. |
required (400) |
liveChatIdRequired |
The liveChatBan resource submitted in the request body must specify a value for the snippet.liveChatId property. |
liveChatMessages
The following tables identify error messages that the API returns in response to calls related to liveChatMessages
resources.
liveChatMessages.delete
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
forbidden |
You do not have the permissions required to delete the specified message. |
forbidden (403) |
modificationNotAllowed |
The specified liveChatMessage resource cannot be deleted. The id parameter might identify a message created by a moderator or another user whose messages cannot be deleted. |
notFound (404) |
liveChatMessageNotFound |
The message that you are trying to delete cannot be found. Check the value of the id parameter to ensure it is correct. |
liveChatMessages.insert
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
forbidden |
You do not have the permissions required to create the specified message. |
forbidden (403) |
liveChatDisabled |
The specified live chat has been disabled by the owner, which means messages cannot be added to the chat. |
forbidden (403) |
liveChatEnded |
The specified live chat is no longer live. |
invalidValue (400) |
messageTextInvalid |
The message text (snippet.textMessageDetails.messageText ) is not valid. |
notFound (404) |
liveChatNotFound |
The live chat identified in the API request does not exist. This error occurs if the chat has been deleted by the owner. |
rateLimitExceeded |
rateLimitExceeded |
The user has posted too many chat messages in a given timeframe. |
required (400) |
liveChatIdRequired |
The liveChatMessage resource must include and specify a value for the snippet.liveChatId property. |
required (400) |
messageTextRequired |
The liveChatMessage resource must include and specify a value for the snippet.textMessageDetails.messageText property. |
required (400) |
typeRequired |
The liveChatMessage resource must include and specify a value for the snippet.type property. Set the parameter value to text |
liveChatMessages.list
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
forbidden |
You do not have the permissions required to retrieve messages for the specified live chat. |
forbidden (403) |
liveChatDisabled |
Live chat is not enabled for the specified broadcast. |
forbidden (403) |
liveChatEnded |
The specified live chat is no longer live. |
notFound (404) |
liveChatNotFound |
The live chat that you are trying to retrieve cannot be found. Check the value of the request’s liveChatId parameter to ensure that it is correct. |
rateLimitExceeded |
rateLimitExceeded |
The request was sent too quickly after the previous request. This error occurs when API requests to retrieve messages are being sent more frequently than YouTube’s refresh rates, which unnecessarily wastes bandwidth. |
liveCuepoints
The following tables identify error messages that the API returns in response to calls related to liveCuepoints
resources.
liveCuepoints.insert
Error type | Error detail | Description |
---|---|---|
invalidValue (400) |
conflictingTimeFields |
Only one of offsetTimeMs and walltime may be specified. |
liveStreams
The following tables identify error messages that the API returns in response to calls related to liveStreams
resources.
liveStreams.delete
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
liveStreamDeletionNotAllowed |
The specified live stream cannot be deleted because it is bound to a broadcast that has still not completed. |
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to delete the specified live stream. For more information, see Implementing OAuth2 authentication. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
notFound (404) |
liveStreamNotFound |
The specified live stream doesn’t exist. |
liveStreams.insert
Error type | Error detail | Description |
---|---|---|
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to create the specified live stream. |
insufficientPermissions |
livePermissionBlocked |
The user that authorized the request is unable to stream live video on YouTube at this time. Details explaining why the user cannot stream live video may be available in the user’s channel settings at https://www.youtube.com/features. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
invalidValue (400) |
invalidDescription |
The snippet.description property’s value in the liveStream resource can have up to 10000 characters. |
invalidValue (400) |
invalidFormat |
The cdn.format property’s value in the liveStream resource is invalid. |
invalidValue (400) |
invalidFrameRate |
The cdn.frameRate property’s value in the liveStream resource is invalid. |
invalidValue (400) |
invalidIngestionType |
The cdn.ingestionType property’s value in the liveStream resource is invalid. |
invalidValue (400) |
invalidResolution |
The cdn.resolution property’s value in the liveStream resource is invalid. |
invalidValue (400) |
invalidTitle |
The snippet.title property’s value in the liveStream resource must be between 1 and 128 characters long. |
rateLimitExceeded |
userRequestsExceedRateLimit |
The user has sent too many requests in a given timeframe. |
required (400) |
cdnRequired |
The liveStream resource must contain the cdn object. |
required (400) |
frameRateRequired |
The API returns this error if you specify a value for the cdn.resolution property but not for the cdn.frameRate property. |
required (400) |
ingestionTypeRequired |
The liveStream resource must specify a value for the cdn.ingestionType property>. |
required (400) |
resolutionRequired |
The API returns this error if you specify a value for the cdn.frameRate property but not for the cdn.resolution property. |
required (400) |
titleRequired |
The liveStream resource must specify a value for the snippet.title property. |
liveStreams.list
Error type | Error detail | Description |
---|---|---|
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to retrieve the specified live stream. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
liveStreams.update
Error type | Error detail | Description |
---|---|---|
forbidden (403) |
liveStreamModificationNotAllowed |
The specified live stream cannot be modified in its current state. For more information, see Life of a Broadcast. |
forbidden (403) |
liveStreamModificationNotAllowed |
The API does not allow you to change the value of the cdn.format , cdn.frameRate , cdn.ingestionType , or cdn.resolution fields after the stream is created. |
forbidden (403) |
liveStreamModificationNotAllowed |
The API does not allow you to change a reusable stream to be non-reusable, or vice versa. For more information, see Understanding Broadcasts and Streams. |
insufficientPermissions |
insufficientLivePermissions |
The request is not authorized to update the specified live stream. For more information, see Implementing OAuth2 authentication. |
insufficientPermissions |
liveStreamingNotEnabled |
The user that authorized the request is not enabled to stream live video on YouTube. The user can find more information at https://www.youtube.com/features. |
invalidValue (400) |
invalidDescription |
The snippet.description property’s value in the liveStream resource can have up to 10000 characters. |
invalidValue (400) |
invalidTitle |
The snippet.title property’s value in the liveStream resource must be between 1 and 128 characters long. |
notFound (404) |
liveStreamNotFound |
The specified live stream doesn’t exist. |
required (400) |
idRequired |
The liveStream resource must specify a value for the id property. |
required (400) |
ingestionTypeRequired |
The liveStream resource must specify a value for the cdn.ingestionType property. |
required (400) |
titleRequired |
The liveStream resource must specify a value for the snippet.title property. |
I’m trying to create Youtube live stream through my webpage via Youtube Data API. Whatever I tried, keep getting that error:
{
"error": {
"code": 400,
"message": "'{0}'",
"errors": [
{
"message": "'{0}'",
"domain": "youtube.part",
"reason": "unknownPart",
"location": "part",
"locationType": "parameter"
}
]
}
}
Unfortunately, this error doesn’t explain anything, and I couldn’t find anything to help me to solve it. I hope someone can explain what is going on here.
I put all relative files down below and added some comments.
web.php
Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');
YoutubeController.php
class YoutubeController extends Controller
{
private $youtube;
public function __construct(Request $request)
{
// like YoutubeStreamService or YoutubeUploadService
$this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
}
public function authenticate($task)
{
return redirect()->away($this->youtube->authenticate($task));
}
public function create(Request $request, $task)
{
$this->youtube->create($request, $task);
}
}
I use an abstract class for authentication codes.
abstract class YoutubeAbstraction
{
// Called from the controller.
// Returns the url to google to authenticate the request.
public function authenticate($task)
{
return $this->client($task)->createAuthUrl();
}
// This code came from mostly Youtueb API documentation.
protected function client($task)
{
$scopes = [
'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
][$task];
$client = new Google_Client();
$client->setApplicationName("MyApp");
$client->setScopes($scopes);
$client->setAuthConfig(base_path("client_secret_{$task}.json"));
$client->setAccessType('offline');
return $client;
}
abstract public function create($request, $task);
}
YoutubeStreamService.php
class YoutubeStreamService extends YoutubeAbstraction
{
// This code came from Youtube API documentation completely.
// It contains only the required fields and their hard-coded values.
public function create($request, $task)
{
$client = $this->client($task);
$client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));
$service = new Google_Service_YouTube($client);
$liveBroadcast = new Google_Service_YouTube_LiveBroadcast();
$liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
$liveBroadcastSnippet->setTitle('my title');
$liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00+03:00');
$liveBroadcast->setSnippet($liveBroadcastSnippet);
$liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
$liveBroadcastStatus->setPrivacyStatus('private');
$liveBroadcast->setStatus($liveBroadcastStatus);
// If I add dd($liveBroadcast) here, I see the object.
// So the error is thrown by the function down below.
$response = $service->liveBroadcasts->insert('', $liveBroadcast);
print_r($response);
}
}
I’m trying to create Youtube live stream through my webpage via Youtube Data API. Whatever I tried, keep getting that error:
{
"error": {
"code": 400,
"message": "'{0}'",
"errors": [
{
"message": "'{0}'",
"domain": "youtube.part",
"reason": "unknownPart",
"location": "part",
"locationType": "parameter"
}
]
}
}
Unfortunately, this error doesn’t explain anything, and I couldn’t find anything to help me to solve it. I hope someone can explain what is going on here.
I put all relative files down below and added some comments.
web.php
Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');
YoutubeController.php
class YoutubeController extends Controller
{
private $youtube;
public function __construct(Request $request)
{
// like YoutubeStreamService or YoutubeUploadService
$this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
}
public function authenticate($task)
{
return redirect()->away($this->youtube->authenticate($task));
}
public function create(Request $request, $task)
{
$this->youtube->create($request, $task);
}
}
I use an abstract class for authentication codes.
abstract class YoutubeAbstraction
{
// Called from the controller.
// Returns the url to google to authenticate the request.
public function authenticate($task)
{
return $this->client($task)->createAuthUrl();
}
// This code came from mostly Youtueb API documentation.
protected function client($task)
{
$scopes = [
'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
][$task];
$client = new Google_Client();
$client->setApplicationName("MyApp");
$client->setScopes($scopes);
$client->setAuthConfig(base_path("client_secret_{$task}.json"));
$client->setAccessType('offline');
return $client;
}
abstract public function create($request, $task);
}
YoutubeStreamService.php
class YoutubeStreamService extends YoutubeAbstraction
{
// This code came from Youtube API documentation completely.
// It contains only the required fields and their hard-coded values.
public function create($request, $task)
{
$client = $this->client($task);
$client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));
$service = new Google_Service_YouTube($client);
$liveBroadcast = new Google_Service_YouTube_LiveBroadcast();
$liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
$liveBroadcastSnippet->setTitle('my title');
$liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00+03:00');
$liveBroadcast->setSnippet($liveBroadcastSnippet);
$liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
$liveBroadcastStatus->setPrivacyStatus('private');
$liveBroadcast->setStatus($liveBroadcastStatus);
// If I add dd($liveBroadcast) here, I see the object.
// So the error is thrown by the function down below.
$response = $service->liveBroadcasts->insert('', $liveBroadcast);
print_r($response);
}
}
#php #laravel #youtube-api #youtube-data-api
#php #laravel #youtube-api #youtube-data-api
Вопрос:
Я пытаюсь создать прямую трансляцию Youtube через свою веб-страницу через API данных Youtube. Что бы я ни пробовал, продолжайте получать эту ошибку:
{
"error": {
"code": 400,
"message": "'{0}'",
"errors": [
{
"message": "'{0}'",
"domain": "youtube.part",
"reason": "unknownPart",
"location": "part",
"locationType": "parameter"
}
]
}
}
К сожалению, эта ошибка ничего не объясняет, и я не смог найти ничего, что помогло бы мне решить ее. Я надеюсь, что кто-нибудь может объяснить, что здесь происходит.
Я поместил все относительные файлы ниже и добавил несколько комментариев.
web.php
Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');
YoutubeController.php
class YoutubeController extends Controller
{
private $youtube;
public function __construct(Request $request)
{
// like YoutubeStreamService or YoutubeUploadService
$this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
}
public function authenticate($task)
{
return redirect()->away($this->youtube->authenticate($task));
}
public function create(Request $request, $task)
{
$this->youtube->create($request, $task);
}
}
Я использую абстрактный класс для кодов аутентификации.
abstract class YoutubeAbstraction
{
// Called from the controller.
// Returns the url to google to authenticate the request.
public function authenticate($task)
{
return $this->client($task)->createAuthUrl();
}
// This code came from mostly Youtueb API documentation.
protected function client($task)
{
$scopes = [
'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
][$task];
$client = new Google_Client();
$client->setApplicationName("MyApp");
$client->setScopes($scopes);
$client->setAuthConfig(base_path("client_secret_{$task}.json"));
$client->setAccessType('offline');
return $client;
}
abstract public function create($request, $task);
}
YoutubeStreamService.php
class YoutubeStreamService extends YoutubeAbstraction
{
// This code came from Youtube API documentation completely.
// It contains only the required fields and their hard-coded values.
public function create($request, $task)
{
$client = $this->client($task);
$client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));
$service = new Google_Service_YouTube($client);
$liveBroadcast = new Google_Service_YouTube_LiveBroadcast();
$liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
$liveBroadcastSnippet->setTitle('my title');
$liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00 03:00');
$liveBroadcast->setSnippet($liveBroadcastSnippet);
$liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
$liveBroadcastStatus->setPrivacyStatus('private');
$liveBroadcast->setStatus($liveBroadcastStatus);
// If I add dd($liveBroadcast) here, I see the object.
// So the error is thrown by the function down below.
$response = $service->liveBroadcasts->insert('', $liveBroadcast);
print_r($response);
}
}
Ответ №1:
Согласно официальной спецификации, ваш вызов LiveBroadcasts.insert
конечной точки API должен включать параметр запроса:
part
(строка)
part
Параметр служит двум целям в этой операции. Он определяет свойства, которые будет устанавливать операция записи, а также свойства, которые будет включать ответ API.
part
Свойства, которые вы можете включить в значение параметраid
,snippet
,contentDetails
, иstatus
.
В PHP это требование сводится к вызову вашего API, подобного приведенному ниже:
$response = $service->liveBroadcasts->insert(
'id,snippet,status', $liveBroadcast);
Комментарии:
1. Спасибо, stvar, я почти сошел с ума.
Почему получаю ошибку?
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "keyExpired",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
Мой код. мне надо вытащить идентификаторы из плей листа и записать в базу
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script>
<title>Document</title>
</head>
<body>
<input type="text" value="PLTI6yRvQqlYq9KoU-NHu43uDmKON7Fsjv" id="searchtext1" size="75">
<button onclick="getVids()">Get Items</button>
<br><br>
<br><br>
<textarea id="area1" style="width:300px;height:500px"> </textarea>
<textarea id="area12" style="width:300px;height:500px;position: relative;float: left"> </textarea>
<script>
sum = 0;
sumN = 1;
var nextPageToken;
function getVids(PageToken){
pid = $('#searchtext1').val();
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part : 'snippet',
maxResults : 50,
playlistId : pid,
pageToken : PageToken,
key: 'Мой токен'
},
function(data){
myPlan(data);
}
);
}
function myPlan(data){
total = data.pageInfo.totalResults;
nextPageToken=data.nextPageToken;
for(i=0;i<data.items.length;i++){
document.getElementById('area1').value +=
sumN + '-' + data.items[i].snippet.title+'n'+
data.items[i].snippet.resourceId.videoId +'nn';
var url = data.items[i].snippet.resourceId.videoId;
$.ajax({
type: "POST",
url: "2.php",
data: {myData: url},
success: function (response) {
document.getElementById('area12').value +=response.length+'-' +response+ "-Ok!!!"+'nn';
}
});
sum++ ; sumN++;
if(sum == (total-1) ){
sum = 0;
return;
}
}
if(sum <(total-1)){
getVids(nextPageToken);
}
}
function init(){
$('#area1').val('');
}
</script>
</body>
</html>
Я пытаюсь создать прямую трансляцию Youtube через свою веб-страницу через API данных Youtube. Что бы я ни пробовал, продолжайте получать эту ошибку:
{
"error": {
"code": 400,
"message": "'{0}'",
"errors": [
{
"message": "'{0}'",
"domain": "youtube.part",
"reason": "unknownPart",
"location": "part",
"locationType": "parameter"
}
]
}
}
К сожалению, эта ошибка ничего не объясняет, и я не смог найти ничего, что помогло бы мне ее решить. Надеюсь, кто-нибудь сможет объяснить, что здесь происходит.
Я поместил все относительные файлы ниже и добавил несколько комментариев.
Web.php
Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');
YoutubeController.php
class YoutubeController extends Controller
{
private $youtube;
public function __construct(Request $request)
{
// like YoutubeStreamService or YoutubeUploadService
$this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
}
public function authenticate($task)
{
return redirect()->away($this->youtube->authenticate($task));
}
public function create(Request $request, $task)
{
$this->youtube->create($request, $task);
}
}
Я использую абстрактный класс для кодов аутентификации.
abstract class YoutubeAbstraction
{
// Called from the controller.
// Returns the url to google to authenticate the request.
public function authenticate($task)
{
return $this->client($task)->createAuthUrl();
}
// This code came from mostly Youtueb API documentation.
protected function client($task)
{
$scopes = [
'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
][$task];
$client = new Google_Client();
$client->setApplicationName("MyApp");
$client->setScopes($scopes);
$client->setAuthConfig(base_path("client_secret_{$task}.json"));
$client->setAccessType('offline');
return $client;
}
abstract public function create($request, $task);
}
YoutubeStreamService.php
class YoutubeStreamService extends YoutubeAbstraction
{
// This code came from Youtube API documentation completely.
// It contains only the required fields and their hard-coded values.
public function create($request, $task)
{
$client = $this->client($task);
$client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));
$service = new Google_Service_YouTube($client);
$liveBroadcast = new Google_Service_YouTube_LiveBroadcast();
$liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
$liveBroadcastSnippet->setTitle('my title');
$liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00+03:00');
$liveBroadcast->setSnippet($liveBroadcastSnippet);
$liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
$liveBroadcastStatus->setPrivacyStatus('private');
$liveBroadcast->setStatus($liveBroadcastStatus);
// If I add dd($liveBroadcast) here, I see the object.
// So the error is thrown by the function down below.
$response = $service->liveBroadcasts->insert('', $liveBroadcast);
print_r($response);
}
}
Некоторые пользователи Windows сообщают, что в конечном итоге они сталкиваются с ошибкой «Не удалось начать потоковую передачу» с OBS при попытке потоковой передачи контента на YouTube. Сообщение об ошибке, сопровождающее ошибку: «Ошибка NVENC: init_encoder: nvEncGetEncodePresetConfig failed: 15 (NV_ENC_ERR_INVALID_VERSION)»
Ошибка «Не удалось начать трансляцию» в OBS
После тщательного изучения этой конкретной проблемы выясняется, что существует несколько различных основных причин, которые могут вызывать этот конкретный код ошибки:
- Отсутствующий / поврежденный распространяемый компонент C ++. Как оказалось, одним из наиболее распространенных случаев, вызывающих эту проблему, является сценарий, при котором либо отсутствует пакет Microsoft C ++ Redistributable 2017, либо тот, который в настоящее время установлен, поврежден. Чтобы решить эту конкретную проблему, необходимо убедиться, что вы правильно установили последнюю версию пакета Microsoft C ++ Redistributable 2017.
- Устаревший графический драйвер. Еще одна потенциальная ситуация, которая может вызвать эту проблему, — это сильно устаревший драйвер графического процессора, из-за которого программному обеспечению OBS сложно поддерживать потоковое соединение с YouTube. В этом случае все, что вам нужно сделать, это установить последние доступные графические драйверы.
- Конфликт с внутриигровым оверлеем. Если вы используете какое-либо программное обеспечение DVR, которое включает функцию наложения, скорее всего, оно будет конфликтовать с функцией кодировщика NVENC, используемой OBS. В этом случае вы можете разрешить конфликт, отключив функцию наложения в игре или удалив конфликтующее программное обеспечение.
Теперь, когда вы хорошо знакомы со всеми основными проблемами, которые могут вызвать ошибку «Не удалось начать потоковую передачу», вот список основных виновников, которые могут быть ответственны за появление этого кода ошибки:
Метод 1: установка распространяемых компонентов Microsoft C ++ для 2017 г.
Как оказалось, одна из наиболее важных зависимостей, потенциально способных вызвать эту проблему, — это отсутствующий или поврежденный пакет Microsoft C ++ Redistributable 2017. Имейте в виду, что этот пакет Visual C ++ чрезвычайно важен для обеспечения того, чтобы OBS могла устанавливать и поддерживать потоковое соединение с YouTube.
Если этот сценарий применим и вы подозреваете, что видите ошибку «Не удалось начать потоковую передачу», возникающую из-за проблемы с Visual C ++, вам следует удалить текущий пакет Reddit Visual C ++ 2017 (если он уже установлен) и выполнить новую установку. с официальных каналов Microsoft.
Вот краткое пошаговое руководство, которое проведет вас через весь процесс:
- Нажмите клавишу Windows + R, чтобы открыть диалоговое окно «Выполнить». Затем введите appwiz.cpl и нажмите Enter, чтобы открыть экран «Программы и компоненты».Открытие меню «Программы и компоненты»
- Зайдя в меню «Программы и компоненты», прокрутите список установленных программ и найдите запись, связанную с распространяемым пакетом Microsoft Visual C ++ 2017.
- Если вы обнаружите, что распространяемый компонент Microsoft Visual C ++ 2017 уже установлен, щелкните его правой кнопкой мыши и выберите «Удалить» в контекстном меню, чтобы от него избавиться.Удаление Microsoft Visual C ++ 2017
Примечание. Если на вашем компьютере не установлен этот распространяемый пакет Visual C ++, пропустите этот и следующий шаг и переходите непосредственно к шагу 5.
- На экране удаления пакета Visual C ++ Redistributable 2017 следуйте инструкциям на экране, чтобы завершить установку, затем перезагрузите компьютер и дождитесь завершения следующего запуска.
- После того, как ваш компьютер загрузится, загрузите один из нижеуказанных пакетов Redist Visual C ++ 2017 в зависимости от архитектуры вашей ОС (32-разрядной или 64-разрядной):
64-разрядный распространяемый компонент Visual C ++ 2017
32-разрядный распространяемый компонент Visual C ++ 2017 - После завершения загрузки дважды щелкните недавно загруженный установщик vc_redist и нажмите Да, если появится запрос учетной записи пользователя UAC. Затем следуйте инструкциям на экране, чтобы завершить установку последней версии распространяемого пакета Microsoft Visual C ++ 2017.Установка Microsoft Visual C ++ 2017
Если эта проблема все еще не устранена или вы уже использовали последнюю версию Microsoft Visual C ++, перейдите к следующему потенциальному исправлению ниже.
Метод 2: обновление графических драйверов
Убедившись, что ошибка «Не удалось начать потоковую передачу» не возникает из-за отсутствия зависимости Visual C ++, следующее, что вам следует изучить, — это графические драйверы.
Как оказалось, некоторые затронутые пользователи говорят, что в их случае основная причина, по которой они не смогли установить потоковое соединение с OBS на Youtube, — это сильно устаревший экземпляр драйверов графического процессора.
В этом случае вы сможете решить проблему, следуя приведенным ниже инструкциям, чтобы обновить текущий драйвер графического процессора, чтобы гарантировать, что OBS имеет все необходимые зависимости для потоковой передачи контента на YouTube:
- Откройте диалоговое окно «Выполнить», нажав клавиши Windows + R. Затем введите «devmgmt.msc» и нажмите Enter, чтобы открыть утилиту «Диспетчер устройств». Когда появится запрос UAC (Контроль учетных записей пользователей), нажмите Да, чтобы предоставить доступ администратора.Открытие утилиты диспетчера устройств
- Когда вы, наконец, войдете в диспетчер устройств, прокрутите список установленных устройств вниз, затем разверните раскрывающееся меню, относящееся к адаптерам дисплея.
- После того, как вы развернете правильное меню, щелкните правой кнопкой мыши драйвер графического процессора, который вы активно используете для требовательных операций рендеринга, и выберите «Обновить драйвер» в только что появившемся контекстном меню.Обновление драйверов графического процессора через диспетчер устройств
Примечание. Если вы столкнулись с проблемой на ноутбуке как с выделенным, так и со встроенным решением, мы рекомендуем обновить оба драйвера графического процессора до последней доступной версии.
- Как только вы перейдете к следующему экрану, нажмите на Автоматический поиск обновленного программного обеспечения драйвера.
Автоматический поиск обновленного программного обеспечения драйвера - Затем дождитесь завершения первоначального сканирования. затем продолжайте и следуйте инструкциям на экране, чтобы завершить установку новой версии драйвера (если определена новая версия).
- Если новая версия драйвера найдена и установлена, перезагрузите компьютер и повторите действие потоковой передачи в OBS после завершения следующего запуска, чтобы увидеть, устранена ли проблема.
Примечание. Если Диспетчер устройств не может найти новую версию для замены текущей, вам также следует использовать проприетарную версию программного обеспечения для обновления от производителя вашей видеокарты, чтобы автоматически найти, загрузить и установить последнюю доступную версию:
GeForce Experience — Nvidia
Адреналин — AMD
Драйвер Intel — Intel
Если вы уже обновили драйвер графического процессора до последней версии, но по-прежнему сталкиваетесь с той же проблемой, перейдите к следующему потенциальному исправлению ниже.
Метод 3: отключение внутриигрового оверлея
Имейте в виду, что если вы используете какое-то программное обеспечение DVR, которое записывает экран и использует какое-то наложение поверх вашего игрового процесса, очень высока вероятность того, что OBS будет конфликтовать с ним, когда они оба попытаются использовать Энкодер NVENC.
Если этот сценарий применим, вы можете решить проблему, отключив внутриигровой оверлей, конфликтующий с программным обеспечением OBS. В большинстве случаев подтверждается, что ошибка «Не удалось начать потоковую передачу» вызвана внутриигровым оверлеем Discord или Nvidia Overlay.
Если вы используете Discord или Nvidia Experience, следуйте инструкциям ниже, чтобы отключить на них функцию наложения.
Если вы используете другой сторонний инструмент наложения, следуйте под-руководству C, чтобы полностью удалить конфликтующее программное обеспечение с вашего компьютера.
A. Отключение функции наложения в Nvidia Experience
- Начните с выключения OBS, затем откройте Nvidia Experience. В следующем меню перейдите на вкладку Общие из списка доступных опций.
- Как только вы окажетесь в следующем меню, перейдите в левое меню и выключите переключатель, связанный с игровым оверлеем.Отключение функции наложения в игре
- После отключения опции сохраните изменения и закройте главное окно Nvidia Experience.
- Снова откройте программное обеспечение OBS и инициируйте еще одну попытку потоковой передачи, чтобы увидеть, устранена ли проблема.
Б. Отключение функции наложения в Discord
- Откройте приложение Discord обычным способом и вызовите основной интерфейс с помощью значка на панели задач.
Примечание. Если вы видите экран сразу же, откройте панель задач и дважды щелкните значок, чтобы открыть окно Discord. - Как только вы войдете в приложение Discord, найдите настройки пользователя (значок шестеренки) в нижней части окна.Доступ к пользовательским настройкам в Discord
- Как только вы окажетесь в меню настроек пользователя, нажмите вкладку «Наложение» в вертикальном меню слева (в разделе «Настройки приложения»).Меню настроек пользователя
- Как только вы окажетесь в меню Overlay, отключите переключатель, связанный с Enable in-game overlay.
Включение внутриигрового оверлея - Сохраните изменения, затем еще раз ODB и посмотрите, устранена ли проблема.
C. Удаление функции наложения из программ и компонентов
- Нажмите клавишу Windows + R, чтобы открыть диалоговое окно «Выполнить». Затем введите appwiz.cpl и нажмите Enter, чтобы открыть меню «Программы и компоненты».Открытие меню «Программы и компоненты»
- В меню «Программы и компоненты» прокрутите список установленных программ и найдите наложенное программное обеспечение, которое вы планируете удалить.
- Когда вы его увидите, щелкните его правой кнопкой мыши и выберите «Удалить» из появившегося контекстного меню.Удаление Nvidia Experience
- На экране удаления следуйте инструкциям на экране, чтобы завершить удаление, а затем перезагрузите компьютер.
- После завершения процедуры запустите игру еще раз и посмотрите, устранена ли проблема.