### Complete Renderer Setup Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_stream_builder.md Demonstrates the complete setup for an audio renderer, including file handling, builder configuration, callback setting, renderer generation, and playback control. Ensure the 'audio.pcm' file exists and is accessible. ```c #include #include #include // Audio data callback int32_t onWriteAudioData(OH_AudioRenderer* renderer, void* userData, void* buffer, int32_t bufferSize) { FILE* audioFile = (FILE*)userData; size_t bytesRead = fread(buffer, 1, bufferSize, audioFile); return bytesRead; } int main() { // Open audio file FILE* audioFile = fopen("audio.pcm", "rb"); if (!audioFile) return -1; // Create builder OH_AudioStreamBuilder* builder = NULL; OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_RENDERER); // Configure OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); OH_AudioStreamBuilder_SetChannelCount(builder, 2); OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE); OH_AudioStreamBuilder_SetEncodingType(builder, AUDIOSTREAM_ENCODING_TYPE_RAW); OH_AudioStreamBuilder_SetLatencyMode(builder, AUDIOSTREAM_LATENCY_MODE_NORMAL); // Set callback OH_AudioStreamBuilder_SetWriteDataCallback(builder, onWriteAudioData, (void*)audioFile); // Generate renderer OH_AudioRenderer* renderer = OH_AudioStreamBuilder_GenerateRenderer(builder); // Destroy builder (no longer needed) OH_AudioStreamBuilder_Destroy(builder); if (!renderer) { fclose(audioFile); return -1; } // Start playback OH_AudioRenderer_Start(renderer); sleep(5); // Play for 5 seconds // Cleanup OH_AudioRenderer_Stop(renderer); OH_AudioRenderer_Release(renderer); fclose(audioFile); return 0; } ``` -------------------------------- ### Basic Video Encoding Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/video_encoder.md Demonstrates the fundamental steps for creating, configuring, and starting a video encoder. This example uses H.264 and sets basic encoding parameters. ```c #include #include int encodeVideo() { OH_AVCodec *encoder = NULL; OH_AVFormat *format = NULL; // Create encoder with H.264 encoder = OH_VideoEncoder_CreateByMime("video/avc"); if (encoder == NULL) { printf("Failed to create encoder\n"); return -1; } // Create format for configuration format = OH_AVFormat_Create(); // Set encoding parameters OH_AVFormat_SetIntValue(format, "width", 1920); OH_AVFormat_SetIntValue(format, "height", 1080); OH_AVFormat_SetIntValue(format, "bitrate", 5000000); // 5 Mbps OH_AVFormat_SetIntValue(format, "frame_rate", 30); // Configure encoder OH_AVErrCode ret = OH_VideoEncoder_Configure(encoder, format); if (ret != AV_ERR_OK) { printf("Failed to configure encoder: %d\n", ret); OH_AVFormat_Destroy(format); OH_VideoEncoder_Destroy(encoder); return -1; } // Start encoding ret = OH_VideoEncoder_Start(encoder); if (ret != AV_ERR_OK) { printf("Failed to start encoder: %d\n", ret); OH_AVFormat_Destroy(format); OH_VideoEncoder_Destroy(encoder); return -1; } // Encode frames... // (frame input handling code here) // Stop encoding OH_VideoEncoder_Stop(encoder); // Cleanup OH_AVFormat_Destroy(format); OH_VideoEncoder_Destroy(encoder); return 0; } ``` -------------------------------- ### Complete Capturer Lifecycle Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_capturer.md Demonstrates the full lifecycle of an audio capturer, including initialization, configuration, starting, pausing, resuming, stopping, and releasing. Ensure microphone permission is granted before execution. The captured audio is saved to '/data/recording.pcm'. ```c #include #include #include #include // Callback for reading captured audio data int32_t onReadAudioData(OH_AudioCapturer* capturer, void* userData, void* buffer, int32_t bufferSize) { // Process captured audio data // Return number of bytes read FILE* outputFile = (FILE*)userData; fwrite(buffer, 1, bufferSize, outputFile); return bufferSize; } int main() { // Check microphone permission if (!OH_AT_CheckSelfPermission("ohos.permission.MICROPHONE")) { printf("Microphone permission not granted\n"); return -1; } // Create builder OH_AudioStreamBuilder* builder = NULL; OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER); // Configure stream for high-quality recording OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); OH_AudioStreamBuilder_SetChannelCount(builder, 2); OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S24LE); OH_AudioStreamBuilder_SetEncodingType(builder, AUDIOSTREAM_ENCODING_TYPE_RAW); OH_AudioStreamBuilder_SetLatencyMode(builder, AUDIOSTREAM_LATENCY_MODE_LOW); // Open output file FILE* outputFile = fopen("/data/recording.pcm", "wb"); if (outputFile == NULL) { OH_AudioStreamBuilder_Destroy(builder); return -1; } // Set read callback OH_AudioStreamBuilder_SetReadDataCallback(builder, onReadAudioData, (void*)outputFile); // Generate capturer OH_AudioCapturer* capturer = OH_AudioStreamBuilder_GenerateCapturer(builder); // Clean up builder OH_AudioStreamBuilder_Destroy(builder); if (capturer == NULL) { printf("Failed to create capturer\n"); fclose(outputFile); return -1; } // Start recording OH_AudioCapturer_Start(capturer); printf("Recording started...\n"); // Record for 10 seconds sleep(10); // Query current state OH_AudioStream_State state; OH_AudioCapturer_GetCurrentState(capturer, &state); printf("Current state: %d\n", state); // Pause recording OH_AudioCapturer_Pause(capturer); printf("Recording paused\n"); sleep(2); // Resume recording OH_AudioCapturer_Start(capturer); printf("Recording resumed\n"); sleep(5); // Stop recording OH_AudioCapturer_Stop(capturer); printf("Recording stopped\n"); // Clean up OH_AudioCapturer_Release(capturer); fclose(outputFile); printf("Recording saved to /data/recording.pcm\n"); return 0; } ``` -------------------------------- ### Example: Dual-Output Video Encoding with Secondary Encoder Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/video_encoder.md Demonstrates how to create a secondary encoder from a primary one, configure both with different parameters, start them, process frames, stop them, and clean up resources. Ensure the secondary encoder is destroyed before the primary encoder. ```c OH_AVCodec *primary = NULL; OH_VideoEncoder_CreatePrimaryWithPreproc("video/avc", &primary); // Create secondary encoder OH_AVCodec *secondary = NULL; OH_AVErrCode result = OH_VideoEncoder_CreateSecondaryFromPrimary( primary, &secondary ); if (result == AV_ERR_OK) { // Configure primary encoder OH_AVFormat *primaryFormat = OH_AVFormat_Create(); OH_AVFormat_SetIntValue(primaryFormat, "width", 1920); OH_AVFormat_SetIntValue(primaryFormat, "height", 1080); OH_VideoEncoder_Configure(primary, primaryFormat); // Configure secondary encoder with different parameters OH_AVFormat *secondaryFormat = OH_AVFormat_Create(); OH_AVFormat_SetIntValue(secondaryFormat, "width", 1280); OH_AVFormat_SetIntValue(secondaryFormat, "height", 720); OH_VideoEncoder_Configure(secondary, secondaryFormat); // Start both OH_VideoEncoder_Start(primary); OH_VideoEncoder_Start(secondary); // Process frames... // Stop both OH_VideoEncoder_Stop(primary); OH_VideoEncoder_Stop(secondary); // Cleanup - secondary first! OH_VideoEncoder_Destroy(secondary); OH_VideoEncoder_Destroy(primary); OH_AVFormat_Destroy(primaryFormat); OH_AVFormat_Destroy(secondaryFormat); } ``` -------------------------------- ### Basic Video Encoding Usage Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/video_encoder.md A C code example demonstrating the basic steps for initializing, configuring, starting, and stopping a video encoder. ```APIDOC ## Usage Example: Basic Video Encoding ### Description This example demonstrates how to create, configure, start, and stop a video encoder using the OpenHarmony C API. ### Code ```c #include #include int encodeVideo() { OH_AVCodec *encoder = NULL; OH_AVFormat *format = NULL; // Create encoder with H.264 encoder = OH_VideoEncoder_CreateByMime("video/avc"); if (encoder == NULL) { printf("Failed to create encoder\n"); return -1; } // Create format for configuration format = OH_AVFormat_Create(); // Set encoding parameters OH_AVFormat_SetIntValue(format, "width", 1920); OH_AVFormat_SetIntValue(format, "height", 1080); OH_AVFormat_SetIntValue(format, "bitrate", 5000000); // 5 Mbps OH_AVFormat_SetIntValue(format, "frame_rate", 30); // Configure encoder OH_AVErrCode ret = OH_VideoEncoder_Configure(encoder, format); if (ret != AV_ERR_OK) { printf("Failed to configure encoder: %d\n", ret); OH_AVFormat_Destroy(format); OH_VideoEncoder_Destroy(encoder); return -1; } // Start encoding ret = OH_VideoEncoder_Start(encoder); if (ret != AV_ERR_OK) { printf("Failed to start encoder: %d\n", ret); OH_AVFormat_Destroy(format); OH_VideoEncoder_Destroy(encoder); return -1; } // Encode frames... // (frame input handling code here) // Stop encoding OH_VideoEncoder_Stop(encoder); // Cleanup OH_AVFormat_Destroy(format); OH_VideoEncoder_Destroy(encoder); return 0; } ``` ``` -------------------------------- ### Complete ArkUI C Interface Integration Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/arkui_interface.md This comprehensive example demonstrates the full integration of the ArkUI C Interface SDK. It covers initializing UI context, querying for Node and Animation APIs, creating and configuring UI nodes, managing the UI hierarchy, and proper cleanup. ```c #include #include #include #include typedef struct { ArkUI_NativeNodeAPI_1* nodeAPI; ArkUI_NativeAnimateAPI_1* animateAPI; ArkUI_NodeHandle rootNode; ArkUI_NodeHandle buttonNode; } UIContext; UIContext* initializeUI() { UIContext* ctx = malloc(sizeof(UIContext)); // Get Node API ctx->nodeAPI = (ArkUI_NativeNodeAPI_1*) OH_ArkUI_QueryModuleInterfaceByName( ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1" ); if (ctx->nodeAPI == NULL) { free(ctx); return NULL; } // Get Animation API ctx->animateAPI = (ArkUI_NativeAnimateAPI_1*) OH_ArkUI_QueryModuleInterfaceByName( ARKUI_NATIVE_ANIMATE, "ArkUI_NativeAnimateAPI_1" ); // Create UI tree ctx->rootNode = ctx->nodeAPI->createNode(ARKUI_NODE_COLUMN); ctx->buttonNode = ctx->nodeAPI->createNode(ARKUI_NODE_BUTTON); // Configure button ArkUI_AttributeItem item = { .string = "Click Me" }; ctx->nodeAPI->setAttribute(ctx->buttonNode, NODE_TEXT_CONTENT, &item); // Add to hierarchy ctx->nodeAPI->insertChild(ctx->rootNode, ctx->buttonNode, 0); return ctx; } void cleanupUI(UIContext* ctx) { if (ctx->rootNode) { ctx->nodeAPI->destroyNode(ctx->rootNode); } free(ctx); } int main() { UIContext* ui = initializeUI(); if (ui == NULL) { printf("Failed to initialize UI\n"); return -1; } // Use UI... cleanupUI(ui); return 0; } ``` -------------------------------- ### ArkUI C Interface SDK Usage Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/arkui_interface.md This example demonstrates how to query and utilize Node, Gesture, and Dialog APIs within the ArkUI C Interface SDK. It includes error handling for API queries and basic node creation. ```c #include #include #include #include int main() { // Query Node API ArkUI_NativeNodeAPI_1* nodeAPI = (ArkUI_NativeNodeAPI_1*)OH_ArkUI_QueryModuleInterfaceByName( ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1" ); if (nodeAPI == NULL) { printf("Failed to get Node API\n"); return -1; } // Create root container (Column) ArkUI_NodeHandle rootNode = nodeAPI->createNode(ARKUI_NODE_COLUMN); if (rootNode == NULL) { printf("Failed to create root node\n"); return -1; } // Create text node ArkUI_NodeHandle textNode = nodeAPI->createNode(ARKUI_NODE_TEXT); ArkUI_AttributeItem item = { .string = "Hello World" }; nodeAPI->setAttribute(textNode, NODE_TEXT_CONTENT, &item); // Add text to root nodeAPI->insertChild(rootNode, textNode, 0); // Query Gesture API for advanced interaction ArkUI_NativeGestureAPI_1* gestureAPI = (ArkUI_NativeGestureAPI_1*)OH_ArkUI_QueryModuleInterfaceByName( ARKUI_NATIVE_GESTURE, "ArkUI_NativeGestureAPI_1" ); if (gestureAPI != NULL) { // Create and configure gestures // (gesture implementation) } // Query Dialog API ArkUI_NativeDialogAPI_1* dialogAPI = (ArkUI_NativeDialogAPI_1*)OH_ArkUI_QueryModuleInterfaceByName( ARKUI_NATIVE_DIALOG, "ArkUI_NativeDialogAPI_1" ); if (dialogAPI != NULL) { // Create and manage dialogs // (dialog implementation) } // Cleanup // (destroy nodes and cleanup) return 0; } ``` -------------------------------- ### Start Audio Renderer Playback Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_renderer.md Initiates audio playback on a configured renderer stream. Ensure the renderer is properly set up with write callbacks before starting. ```c // After configuring the renderer and setting up write callbacks OH_AudioStream_Result result = OH_AudioRenderer_Start(renderer); if (result != AUDIOSTREAM_SUCCESS) { // Handle error } ``` -------------------------------- ### Start Audio Capturer Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_capturer.md Starts the audio capturer stream to begin recording. Ensure a read callback is registered before starting. Requires the MICROPHONE permission. ```c #include // After configuring the capturer with builder OH_AudioStream_Result result = OH_AudioCapturer_Start(capturer); if (result != AUDIOSTREAM_SUCCESS) { printf("Failed to start capturer: %d\n", result); // Handle error } // Now audio is being captured and read callback will be invoked ``` -------------------------------- ### Builder Pattern Usage Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/README.md Illustrates the typical lifecycle of using configuration builders for audio streams: Create, Configure, Generate, Use, and Release. ```text Create → Configure → Generate → Use → Release ``` -------------------------------- ### Example: CheckSelfPermission Usage in C Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/access_token.md Demonstrates how to use OH_AT_CheckSelfPermission to check for internet and location permissions. Handles both granted and denied scenarios. ```c #include #include #include int main() { // Check for internet permission bool hasInternetPerm = OH_AT_CheckSelfPermission("ohos.permission.INTERNET"); if (hasInternetPerm) { printf("Internet permission is granted\n"); // Proceed with network operations } else { printf("Internet permission is denied\n"); // Handle permission denial } // Check for location permission bool hasLocationPerm = OH_AT_CheckSelfPermission("ohos.permission.LOCATION"); if (hasLocationPerm) { printf("Location permission is granted\n"); // Proceed with location services } else { printf("Location permission is denied\n"); } return 0; } ``` -------------------------------- ### Audio Stream Builder Pattern Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/configuration.md Demonstrates the usage of the Audio Stream Builder to configure and generate an audio renderer. ```APIDOC ## Audio Stream Builder Pattern Example This example shows how to use the `OH_AudioStreamBuilder` to configure audio stream parameters and generate a renderer. ### Code Example ```c #include // Create builder OH_AudioStreamBuilder* builder; OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_RENDERER); // Configure parameters OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); OH_AudioStreamBuilder_SetChannelCount(builder, 2); OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE); // Generate stream OH_AudioRenderer* renderer = OH_AudioStreamBuilder_GenerateRenderer(builder); // Cleanup OH_AudioStreamBuilder_Destroy(builder); ``` ### Usage 1. **Create Builder**: Initialize an `OH_AudioStreamBuilder` instance using `OH_AudioStreamBuilder_Create`. 2. **Configure Parameters**: Set desired audio stream properties like sampling rate, channel count, and sample format using dedicated builder functions. 3. **Generate Stream**: Create the audio renderer or capturer using `OH_AudioStreamBuilder_GenerateRenderer` or `OH_AudioStreamBuilder_GenerateCapturer`. 4. **Cleanup**: Release the builder resources using `OH_AudioStreamBuilder_Destroy`. ``` -------------------------------- ### Complete Audio Renderer Lifecycle Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_renderer.md Demonstrates the complete lifecycle of an audio renderer, from creation and configuration to playback control and cleanup. This includes setting stream properties, handling audio data writes, and managing playback states. ```c #include #include #include // Callback for writing audio data int32_t onWriteAudioData(OH_AudioRenderer* renderer, void* userData, void* buffer, int32_t bufferSize) { // Fill buffer with audio data // Return number of bytes written return bufferSize; } int main() { // Create builder OH_AudioStreamBuilder* builder = OH_AudioStreamBuilder_Create( AUDIOSTREAM_TYPE_RENDERER); // Configure stream OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); OH_AudioStreamBuilder_SetChannelLayout(builder, AUDIO_CHANNEL_LAYOUT_STEREO); OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE); // Set write callback OH_AudioStreamBuilder_SetWriteDataCallback(builder, onWriteAudioData, NULL); // Generate renderer OH_AudioRenderer* renderer = OH_AudioStreamBuilder_GenerateRenderer(builder); // Start playback OH_AudioRenderer_Start(renderer); // Get current state OH_AudioStream_State state; OH_AudioRenderer_GetCurrentState(renderer, &state); // Pause if needed OH_AudioRenderer_Pause(renderer); // Resume OH_AudioRenderer_Start(renderer); // Stop playback OH_AudioRenderer_Stop(renderer); // Clean up OH_AudioRenderer_Release(renderer); OH_AudioStreamBuilder_Destroy(builder); return 0; } ``` -------------------------------- ### Handle Illegal State: Starting Running Stream Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/errors.md Illustrates the AUDIOSTREAM_ERROR_ILLEGAL_STATE error that occurs when attempting to start an audio stream that is already running. ```c // Trying to start an already running stream OH_AudioRenderer_Start(renderer); // Success OH_AudioRenderer_Start(renderer); // AUDIOSTREAM_ERROR_ILLEGAL_STATE ``` -------------------------------- ### Handle Unsupported Format Error Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/errors.md Shows an example where setting an unsupported sample rate and format for an audio stream configuration leads to an AUDIOSTREAM_ERROR_UNSUPPORTED_FORMAT. ```c // Unsupported sample format OH_AVFormat_SetIntValue(format, "sample-rate", 192000); OH_AVFormat_SetIntValue(format, "sample-format", AUDIOSTREAM_SAMPLE_F16LE); // Not supported ``` -------------------------------- ### OH_AudioRenderer_Start Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_renderer.md Starts playback on the audio renderer stream. This should be called after the renderer has been configured and is ready to play audio data. ```APIDOC ## OH_AudioRenderer_Start ### Description Start playback on the renderer stream. ### Method `OH_AudioRenderer_Start` ### Parameters #### Path Parameters - `renderer` (OH_AudioRenderer*) - Required - Renderer instance ### Return Result code indicating success or error. ### Throws - `AUDIOSTREAM_ERROR_INVALID_PARAM` if renderer is null - `AUDIOSTREAM_ERROR_ILLEGAL_STATE` if stream is already running or in an invalid state ### Example ```c // After configuring the renderer and setting up write callbacks OH_AudioStream_Result result = OH_AudioRenderer_Start(renderer); if (result != AUDIOSTREAM_SUCCESS) { // Handle error } ``` ``` -------------------------------- ### Check and Handle Permissions in C Application Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/access_token.md Demonstrates how to check for critical permissions during application initialization and before performing sensitive operations. Provides examples of disabling features or showing user messages when permissions are not granted. ```c // In activity/page initialization void onAppInit() { // Check critical permissions if (!OH_AT_CheckSelfPermission("ohos.permission.INTERNET")) { // Disable network-dependent features disableNetworkFeatures(); } // Initialize features based on available permissions } // Before performing protected operation void performSensitiveOperation() { if (OH_AT_CheckSelfPermission("ohos.permission.READ_MEDIA")) { // Access media files } else { // Show user message about missing permission } } ``` -------------------------------- ### OH_AudioCapturer_Start Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_capturer.md Starts the audio capturer stream, transitioning it from a stopped state to a running state to begin audio capture. The application must have a read callback registered to receive captured audio data. ```APIDOC ## OH_AudioCapturer_Start ### Description Starts recording on the capturer stream. ### Method `OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **capturer** (`OH_AudioCapturer*`) - Required - Capturer instance created via `OH_AudioStreamBuilder_GenerateCapturer()` ### Return - `OH_AudioStream_Result` — Result code indicating success or error. ### Permissions Required - `ohos.permission.MICROPHONE` ### Throws - `AUDIOSTREAM_ERROR_INVALID_PARAM` if capturer is null - `AUDIOSTREAM_ERROR_ILLEGAL_STATE` if stream is already running or in an invalid state ### Description Transitions the capturer from stopped state to running state, beginning audio capture. The application must have already registered a read callback via `OH_AudioStreamBuilder_SetReadDataCallback()` to receive captured audio data. ### Request Example ```c #include // After configuring the capturer with builder OH_AudioStream_Result result = OH_AudioCapturer_Start(capturer); if (result != AUDIOSTREAM_SUCCESS) { printf("Failed to start capturer: %d\n", result); // Handle error } // Now audio is being captured and read callback will be invoked ``` ### Response #### Success Response (AUDIOSTREAM_SUCCESS) - None #### Response Example - None ``` -------------------------------- ### Setting Text Content with ArkUI_AttributeItem Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/types.md Example demonstrating how to use ArkUI_AttributeItem to set a string attribute, specifically text content for a node. ```c // Setting text content ArkUI_AttributeItem item = { .string = "Hello" }; setAttribute(node, NODE_TEXT_CONTENT, &item); ``` -------------------------------- ### Video Codec Error Handling Example Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/errors.md Demonstrates how to handle potential errors when creating a video encoder using OH_VideoEncoder_CreatePrimaryWithPreproc. Includes checks for common errors like invalid values, memory allocation failures, and unsupported codecs. ```c OH_AVCodec *encoder = NULL; OH_AVErrCode result = OH_VideoEncoder_CreatePrimaryWithPreproc( "video/avc", &encoder ); switch (result) { case AV_ERR_OK: // Successfully created break; case AV_ERR_INVALID_VAL: printf("Invalid MIME type or codec pointer\n"); return -1; case AV_ERR_NO_MEMORY: printf("Memory allocation failed\n"); return -1; case AV_ERR_UNSUPPORTED: printf("H.264 encoding not supported on this device\n"); // Try H.265 instead result = OH_VideoEncoder_CreateByMime("video/hevc", &encoder); break; default: printf("Unknown error: %d\n", result); return -1; } ``` -------------------------------- ### Handle Resource Errors (AV_ERR_NO_MEMORY) Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/errors.md When encountering memory allocation errors, attempt to free up resources before retrying the operation. This example shows releasing unused buffers and garbage collection. ```c // Try to free resources and retry OH_AVErrCode result = OH_VideoEncoder_CreateByMime("video/avc", &encoder); if (result == AV_ERR_NO_MEMORY) { // Release other resources releaseUnusedBuffers(); gc(); // Retry result = OH_VideoEncoder_CreateByMime("video/avc", &encoder); } ``` -------------------------------- ### OH_AudioCapturer_Stop Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_capturer.md Stops the audio capturer stream and resets its position. After stopping, the stream must be started again or properly released. ```APIDOC ## OH_AudioCapturer_Stop ### Description Stop the capturer stream and reset position. ### Method `OH_AudioStream_Result OH_AudioCapturer_Stop(OH_AudioCapturer* capturer)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **capturer** (`OH_AudioCapturer*`) - Required - Capturer instance ### Return - `OH_AudioStream_Result` ### Permissions Required - `ohos.permission.MICROPHONE` ### Throws - `AUDIOSTREAM_ERROR_INVALID_PARAM` if capturer is null - `AUDIOSTREAM_ERROR_ILLEGAL_STATE` if stream is in an invalid state ### Description Stops audio capture and resets the stream position. After stopping, the stream must be started again or properly released. ### Request Example ```c OH_AudioStream_Result result = OH_AudioCapturer_Stop(capturer); if (result == AUDIOSTREAM_SUCCESS) { // Recording has stopped // Audio data in the input queue is discarded } ``` ### Response #### Success Response (AUDIOSTREAM_SUCCESS) - None #### Response Example - None ``` -------------------------------- ### Create and Configure a Text Node Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/arkui_native_node.md Demonstrates how to create a text node, set its content, and add it to a parent node using the ArkUI Native Node API. ```c #include #include // Get the native node API ArkUI_NativeNodeAPI_1* nodeApi = (ArkUI_NativeNodeAPI_1*)OH_ArkUI_QueryModuleInterfaceByName( ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"); // Create a text node ArkUI_NodeHandle textNode = nodeApi->createNode(ARKUI_NODE_TEXT); // Set text content ArkUI_AttributeItem item = { .string = "Hello World" }; nodeApi->setAttribute(textNode, NODE_TEXT_CONTENT, &item); // Add the node to a parent (typically a container) nodeApi->insertChild(parentNode, textNode, 0); ``` -------------------------------- ### Configure Video Encoder Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/configuration.md Sets up a video encoder with specified parameters like resolution, bitrate, and frame rate. Ensure necessary headers are included. ```c #include #include int setupVideoEncoding() { OH_AVCodec *encoder = NULL; OH_AVFormat *format = NULL; // Create encoder encoder = OH_VideoEncoder_CreateByMime("video/avc"); if (encoder == NULL) { return -1; } // Create format format = OH_AVFormat_Create(); if (format == NULL) { OH_VideoEncoder_Destroy(encoder); return -1; } // Configure video parameters OH_AVFormat_SetIntValue(format, "width", 1920); OH_AVFormat_SetIntValue(format, "height", 1080); OH_AVFormat_SetIntValue(format, "bitrate", 5000000); // 5 Mbps OH_AVFormat_SetIntValue(format, "frame_rate", 30); OH_AVFormat_SetIntValue(format, "i_frame_interval", 1); // 1 second // Configure encoder OH_AVErrCode ret = OH_VideoEncoder_Configure(encoder, format); if (ret != AV_ERR_OK) { OH_AVFormat_Destroy(format); OH_VideoEncoder_Destroy(encoder); return -1; } // Start encoding OH_VideoEncoder_Start(encoder); // ... supply frames ... // Cleanup OH_VideoEncoder_Stop(encoder); OH_AVFormat_Destroy(format); OH_VideoEncoder_Destroy(encoder); return 0; } ``` -------------------------------- ### Create a Button with Click Event Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/arkui_native_node.md Shows how to create a button node, set its text, and register a callback function for click events. ```c // Create button node ArkUI_NodeHandle buttonNode = nodeApi->createNode(ARKUI_NODE_BUTTON); // Set button text ArkUI_AttributeItem textItem = { .string = "Click Me" }; nodeApi->setAttribute(buttonNode, NODE_TEXT_CONTENT, &textItem); // Register click event handler void onButtonClick(ArkUI_NodeHandle node, void* userData) { // Handle button click } nodeApi->registerNodeEventReceiver(buttonNode, NODE_CLICK_EVENT, onButtonClick, NULL); ``` -------------------------------- ### Setting Numeric Value with ArkUI_AttributeItem Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/types.md Example showing how to use ArkUI_AttributeItem to set a numeric attribute, such as a node's width, using a numeric array. ```c // Setting numeric value ArkUI_NumberValue nums[] = { 100.0f }; ArkUI_AttributeItem item = { .value = nums, .size = 1 }; setAttribute(node, NODE_WIDTH, &item); ``` -------------------------------- ### Create and Configure Text Component Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/MODULE_GUIDE.md This C code snippet demonstrates how to obtain the Native Node API, create a text component, set its content, and insert it into a parent node. Ensure the ARKUI_NATIVE_NODE constant and ArkUI_NativeNodeAPI_1 structure are available. ```c // Get Node API ArkUI_NativeNodeAPI_1* api = (ArkUI_NativeNodeAPI_1*)OH_ArkUI_QueryModuleInterfaceByName( ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"); // Create component ArkUI_NodeHandle node = api->createNode(ARKUI_NODE_TEXT); // Configure ArkUI_AttributeItem item = { .string = "Hello" }; api->setAttribute(node, NODE_TEXT_CONTENT, &item); // Add to parent api->insertChild(parent, node, 0); ``` -------------------------------- ### OH_AVFormat Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/types.md An opaque handle used for managing format and configuration information for codecs. It is utilized for codec setup, capability queries, and frame-level parameter specifications. ```APIDOC ## OH_AVFormat ### Description Opaque handle for format/configuration information. ### Type Definition ```c typedef struct OH_AVFormat OH_AVFormat; ``` ### Details Holds codec configuration parameters and metadata. Used in: - Codec configuration before starting - Capability queries - Frame-level parameter specification ### Lifetime Created with `OH_AVFormat_Create()`, destroyed with `OH_AVFormat_Destroy()`. ``` -------------------------------- ### Creating a Button with Click Event Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/arkui_native_node.md Illustrates how to create a button, set its text, and register a click event listener. ```APIDOC ## Creating a Button with Click Event ### Description This example demonstrates creating a button node, setting its text content, and registering a callback function to handle click events. ### Method `nodeApi->createNode(ARKUI_NODE_BUTTON)` `nodeApi->setAttribute(buttonNode, NODE_TEXT_CONTENT, &textItem)` `nodeApi->registerNodeEventReceiver(buttonNode, NODE_CLICK_EVENT, onButtonClick, NULL)` ### Parameters #### `createNode` - **nodeType** (ArkUI_NodeType) - Required - Specifies the type of node to create, e.g., `ARKUI_NODE_BUTTON`. #### `setAttribute` - **nodeHandle** (ArkUI_NodeHandle) - Required - The handle to the node to modify. - **attributeId** (ArkUI_AttributeId) - Required - The identifier of the attribute to set, e.g., `NODE_TEXT_CONTENT`. - **attributeItem** (ArkUI_AttributeItem*) - Required - A pointer to the attribute item containing the new value. #### `registerNodeEventReceiver` - **nodeHandle** (ArkUI_NodeHandle) - Required - The handle to the node to register the event for. - **event** (ArkUI_NodeEvent) - Required - The type of event to listen for, e.g., `NODE_CLICK_EVENT`. - **callback** (void*) - Required - A pointer to the callback function to be executed when the event occurs. - **userData** (void*) - Optional - User-defined data to be passed to the callback function. ### Request Example ```c // Create button node ArkUI_NodeHandle buttonNode = nodeApi->createNode(ARKUI_NODE_BUTTON); // Set button text ArkUI_AttributeItem textItem = { .string = "Click Me" }; nodeApi->setAttribute(buttonNode, NODE_TEXT_CONTENT, &textItem); // Register click event handler void onButtonClick(ArkUI_NodeHandle node, void* userData) { // Handle button click } nodeApi->registerNodeEventReceiver(buttonNode, NODE_CLICK_EVENT, onButtonClick, NULL); ``` ``` -------------------------------- ### Get Audio Renderer Sampling Rate Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_renderer.md Query the sampling rate of the renderer stream. Ensure the renderer and rate pointers are valid to avoid errors. ```c OH_AudioStream_Result OH_AudioRenderer_GetSamplingRate( OH_AudioRenderer* renderer, int32_t* rate ); ``` ```c int32_t sampleRate; OH_AudioRenderer_GetSamplingRate(renderer, &sampleRate); // sampleRate will contain value like 44100 or 48000 ``` -------------------------------- ### Get Current Audio Renderer State Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_renderer.md Retrieves the current operational state of the audio renderer. The state can be checked against predefined constants like `AUDIOSTREAM_STATE_RUNNING`. ```c OH_AudioStream_State currentState; OH_AudioStream_Result result = OH_AudioRenderer_GetCurrentState(renderer, ¤tState); if (result == AUDIOSTREAM_SUCCESS) { if (currentState == AUDIOSTREAM_STATE_RUNNING) { // Stream is actively playing } } ``` -------------------------------- ### Creating a Text Node Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/arkui_native_node.md Demonstrates how to create a text node, set its content, and add it to the node tree. ```APIDOC ## Creating a Text Node ### Description This example shows how to create a text node, set its content using `setAttribute`, and insert it into a parent node. ### Method `nodeApi->createNode(ARKUI_NODE_TEXT)` `nodeApi->setAttribute(textNode, NODE_TEXT_CONTENT, &item)` `nodeApi->insertChild(parentNode, textNode, 0)` ### Parameters #### `createNode` - **nodeType** (ArkUI_NodeType) - Required - Specifies the type of node to create, e.g., `ARKUI_NODE_TEXT`. #### `setAttribute` - **nodeHandle** (ArkUI_NodeHandle) - Required - The handle to the node to modify. - **attributeId** (ArkUI_AttributeId) - Required - The identifier of the attribute to set, e.g., `NODE_TEXT_CONTENT`. - **attributeItem** (ArkUI_AttributeItem*) - Required - A pointer to the attribute item containing the new value. #### `insertChild` - **parentNode** (ArkUI_NodeHandle) - Required - The handle to the parent node. - **childNode** (ArkUI_NodeHandle) - Required - The handle to the child node to insert. - **index** (int) - Required - The position at which to insert the child node. ### Request Example ```c #include #include // Get the native node API ArkUI_NativeNodeAPI_1* nodeApi = (ArkUI_NativeNodeAPI_1*)OH_ArkUI_QueryModuleInterfaceByName( ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"); // Create a text node ArkUI_NodeHandle textNode = nodeApi->createNode(ARKUI_NODE_TEXT); // Set text content ArkUI_AttributeItem item = { .string = "Hello World" }; nodeApi->setAttribute(textNode, NODE_TEXT_CONTENT, &item); // Add the node to a parent (typically a container) nodeApi->insertChild(parentNode, textNode, 0); ``` ``` -------------------------------- ### Get Audio Capturer Stream ID Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_capturer.md Queries the stream ID of the capturer. This ID can be used for stream-specific operations. Ensure the capturer and streamId pointers are valid. ```c uint32_t streamId; OH_AudioCapturer_GetStreamId(capturer, &streamId); // Use streamId for stream-specific operations ``` -------------------------------- ### Audio Renderer C API Usage Flow Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/MODULE_GUIDE.md Illustrates the typical sequence of C API calls for audio playback. Ensure necessary permissions are granted before use. ```text 1. Create builder (OH_AudioStreamBuilder_Create) 2. Configure parameters (SetSamplingRate, SetChannelCount, etc.) 3. Register callback (SetWriteDataCallback or SetReadDataCallback) 4. Generate stream (GenerateRenderer or GenerateCapturer) 5. Destroy builder (OH_AudioStreamBuilder_Destroy) — optional, independent 6. Control stream (Start, Stop, Pause, etc.) 7. Query state (GetCurrentState, GetSamplingRate, etc.) 8. Release stream (Release) ``` -------------------------------- ### Get Audio Capturer Sampling Rate Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_capturer.md Queries the sampling rate of the capturer in Hz. This value reflects the configured sampling rate. Ensure the capturer and rate pointers are valid. ```c int32_t sampleRate; OH_AudioCapturer_GetSamplingRate(capturer, &sampleRate); // sampleRate contains the configured rate (e.g., 48000) ``` -------------------------------- ### Configure and Generate Audio Renderer Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/configuration.md Use this snippet to set up an audio stream builder for playback. It configures parameters like sampling rate, channel count, sample format, encoding type, and latency mode before generating an audio renderer. ```c #include #include int setupAudioPlayback() { OH_AudioStreamBuilder* builder = NULL; OH_AudioRenderer* renderer = NULL; // Create builder for renderer OH_AudioStream_Result ret = OH_AudioStreamBuilder_Create( &builder, AUDIOSTREAM_TYPE_RENDERER ); if (ret != AUDIOSTREAM_SUCCESS) { return -1; } // Configure for CD-quality stereo playback OH_AudioStreamBuilder_SetSamplingRate(builder, 44100); OH_AudioStreamBuilder_SetChannelCount(builder, 2); // Stereo OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE); OH_AudioStreamBuilder_SetEncodingType(builder, AUDIOSTREAM_ENCODING_TYPE_RAW); OH_AudioStreamBuilder_SetLatencyMode(builder, AUDIOSTREAM_LATENCY_MODE_NORMAL); // Set write callback to supply audio data OH_AudioStreamBuilder_SetWriteDataCallback(builder, onWriteAudioData, NULL); // Generate renderer from configuration renderer = OH_AudioStreamBuilder_GenerateRenderer(builder); if (renderer == NULL) { OH_AudioStreamBuilder_Destroy(builder); return -1; } // Cleanup builder (renderer is independent) OH_AudioStreamBuilder_Destroy(builder); // Start playback OH_AudioRenderer_Start(renderer); // ... use renderer ... // Cleanup OH_AudioRenderer_Stop(renderer); OH_AudioRenderer_Release(renderer); return 0; } ``` -------------------------------- ### Get Audio Capturer Latency Mode Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_capturer.md Queries the latency mode of the capturer. This returns the latency mode that was set during the builder configuration. Ensure the capturer and latencyMode pointers are valid. ```c OH_AudioStream_LatencyMode mode; OH_AudioCapturer_GetLatencyMode(capturer, &mode); // Returns the latency mode set during builder configuration ``` -------------------------------- ### Access Feature Based on Permissions Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/access_token.md Controls access to a feature, such as starting a video call, by checking for necessary permissions (CAMERA and MICROPHONE). If permissions are missing, it prints messages indicating which are required. ```c #include #include void startVideoCall() { bool cameraGranted = OH_AT_CheckSelfPermission("ohos.permission.CAMERA"); bool micGranted = OH_AT_CheckSelfPermission("ohos.permission.MICROPHONE"); if (cameraGranted && micGranted) { printf("Starting video call...\n"); // Initialize camera and microphone } else { if (!cameraGranted) { printf("Camera permission required\n"); } if (!micGranted) { printf("Microphone permission required\n"); } // Request permissions through proper channel or disable feature } } ``` -------------------------------- ### Safe Resource Cleanup Pattern Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/index.md This C code snippet demonstrates the recommended pattern for safely cleaning up audio renderer resources. It ensures that resources are stopped and released before being set to NULL. ```c // Always follow this pattern for safe cleanup: OH_AudioRenderer* renderer = /* created */; if (renderer != NULL) { OH_AudioRenderer_Stop(renderer); OH_AudioRenderer_Release(renderer); renderer = NULL; } ``` -------------------------------- ### Configure Audio Stream with Builder Pattern Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/configuration.md Use the audio stream builder to configure parameters such as sampling rate, channel count, and sample format before generating an audio renderer or capturer. Remember to create and destroy the builder instance. ```c #include // Create builder OH_AudioStreamBuilder* builder; OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_RENDERER); // Configure parameters OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); OH_AudioStreamBuilder_SetChannelCount(builder, 2); OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE); // Generate stream OH_AudioRenderer* renderer = OH_AudioStreamBuilder_GenerateRenderer(builder); // Cleanup OH_AudioStreamBuilder_Destroy(builder); ``` -------------------------------- ### Codec State Machine Transitions Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/README.md Details the state transitions for codec APIs, from CREATED through CONFIGURED and RUNNING to STOPPED and released. ```text Codec: CREATED → CONFIGURED → RUNNING → STOPPED → released ``` -------------------------------- ### Build a Horizontal Layout Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/arkui_native_node.md Illustrates the creation of a horizontal layout (Row) and adding child nodes to it. ```c // Create a row (horizontal layout) ArkUI_NodeHandle rowNode = nodeApi->createNode(ARKUI_NODE_ROW); // Create child components ArkUI_NodeHandle text1 = nodeApi->createNode(ARKUI_NODE_TEXT); ArkUI_NodeHandle text2 = nodeApi->createNode(ARKUI_NODE_TEXT); // Add children to row nodeApi->insertChild(rowNode, text1, 0); nodeApi->insertChild(rowNode, text2, 1); ``` -------------------------------- ### Create AVFormat for Encoder Configuration Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/MODULE_GUIDE.md This C code snippet demonstrates how to create an OH_AVFormat object and set essential parameters for video encoder configuration, such as resolution, bitrate, and frame rate. ```c OH_AVFormat* format = OH_AVFormat_Create(); OH_AVFormat_SetIntValue(format, "width", 1920); OH_AVFormat_SetIntValue(format, "height", 1080); OH_AVFormat_SetIntValue(format, "bitrate", 5000000); OH_AVFormat_SetIntValue(format, "frame_rate", 30); ``` -------------------------------- ### Set Audio Sample Format Source: https://github.com/openharmony/interface_sdk_c/blob/master/_autodocs/api-reference/audio_stream_builder.md Configures the PCM sample format for the audio stream. Use AUDIOSTREAM_SAMPLE_S16LE for standard use cases or AUDIOSTREAM_SAMPLE_F32LE for float processing. ```c OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE); OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_F32LE); ```