Before API development, you need to make necessary development preparations, ensure that the Maven repository address of the HMS Core SDK has been configured in your project, and the SDK of this service has been integrated.
1. Create and initialize an audio transcription engine, and create an audio file transcription configurator.
- // Create an audio transcription engine.
- MLRemoteAftEngine engine = MLRemoteAftEngine.getInstance();
- // Initialize the engine and pass the current context.
- engine.init(this);
- // Create an audio file transcription configurator.
- MLRemoteAftSetting setting = new MLRemoteAftSetting.Factory()
- // Set the transcription language code, complying with the BCP 47 standard. Currently, zh (Chinese) and en-US (English) are supported.
- .setLanguageCode("zh")
- .create();
2. Create a listener callback to process the audio file transcription result. (The duration of a to-be-processed audio file cannot be longer than 1 minute.)
- private MLRemoteAftListener aftListener = new MLRemoteAftListener() {
- public void onResult(String taskId, MLRemoteAftResult result, Object ext) {
- // Obtain the transcription result notification.
- if (result.isComplete()) {
- // Process the transcription result.
- }
- }
- @Override
- public void onError(String taskId, int errorCode, String message) {
- // Transcription error callback function.
- }
- @Override
- public void onInitComplete(String taskId, Object ext) {
- // Reserved.
- }
- @Override
- public void onUploadProgress(String taskId, double progress, Object ext) {
- // Reserved.
- }
- @Override
- public void onEvent(String taskId, int eventId, Object ext) {
- // Reserved.
- }
- };
3. Pass the listener callback function to the created audio transcription engine.
- engine.setAftListener(aftListener);
4. Use the shortRecognize method to pass locally obtained audio files or audio files recorded using a recorder to the audio transcription engine.
- // uri indicates audio resources read from the local storage or recorder. Only local audio files with duration (not longer than 1 minute) whose URIs starting with content:// or file:// are supported.
- engine.shortRecognize(uri, setting);