GoogleCloudPlatform / android-docs-samples

Apache License 2.0
375 stars 596 forks source link

API is not giving any result. #126

Open Abhi55Y opened 4 years ago

Abhi55Y commented 4 years ago

I am working on a project where I have to transcribe a prerecorded audio file. I tried using your demo project but it didn't work for me, then I tried making another app but it is not giving me any result. I am commenting the code and my sample files below.

Abhi55Y commented 4 years ago

build.gradle(project) // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

repositories {
    google()
    jcenter()

}
dependencies {
    classpath 'com.android.tools.build:gradle:3.6.3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

}

allprojects { repositories { google() jcenter()

}

}

task clean(type: Delete) { delete rootProject.buildDir }

build.gradle(Module:app) apply plugin: 'com.android.application'

android { compileSdkVersion 29 buildToolsVersion "29.0.3"

defaultConfig {
    applicationId "com.example.googlespeech"
    minSdkVersion 19
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

}

dependencies { implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.api-client:google-api-client-android:1.22.0'
implementation 'com.google.apis:google-api-services-speech:v1beta1-rev336-1.22.0'
implementation 'com.google.apis:google-api-services-language:v1beta2-rev6-1.22.0'
implementation 'com.google.code.findbugs:jsr305:2.0.1'
implementation 'commons-io:commons-io:2.5'

}

AndroidMenifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.googlespeech">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

MainActivity.java package com.example.googlespeech;

import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;

import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64; import com.google.api.services.speech.v1beta1.Speech; import com.google.api.services.speech.v1beta1.SpeechRequestInitializer; import com.google.api.services.speech.v1beta1.model.RecognitionAudio; import com.google.api.services.speech.v1beta1.model.RecognitionConfig; import com.google.api.services.speech.v1beta1.model.SpeechRecognitionResult; import com.google.api.services.speech.v1beta1.model.SyncRecognizeRequest; import com.google.api.services.speech.v1beta1.model.SyncRecognizeResponse;

import org.apache.commons.io.IOUtils;

import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream;

public class MainActivity extends AppCompatActivity { //private Uri soundUri; private final String CLOUD_API_KEY = "Api Key"; private String base64EncodedData; private TextView speechToTextResult; private Button browseButton;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    browseButton = (Button)findViewById(R.id.browse_button);
    speechToTextResult = (TextView) findViewById(R.id.speech_to_text_result);

    browseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent filePicker = new Intent(Intent.ACTION_GET_CONTENT);
            filePicker.setType("audio/*");
            startActivityForResult(filePicker, 1);
        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK) {
        final Uri soundUri = data.getData();

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    assert soundUri != null;
                    InputStream stream = getContentResolver().openInputStream(soundUri);
                    byte[] audioData = IOUtils.toByteArray(stream);
                    stream.close();

                    base64EncodedData = Base64.encodeBase64String(audioData);

                }
                catch (FileNotFoundException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

                MediaPlayer player = new MediaPlayer();
                try
                {
                    player.setDataSource(MainActivity.this, soundUri);
                    player.prepare();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

                player.start();

                // Release the player
                player.setOnCompletionListener(
                        new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {
                                mediaPlayer.release();
                            }
                        });

                Speech speechService = new Speech.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null).setSpeechRequestInitializer(new SpeechRequestInitializer(CLOUD_API_KEY)).build();

                RecognitionConfig recognitionConfig = new RecognitionConfig();
                recognitionConfig.setLanguageCode("en-IN");

                RecognitionAudio recognitionAudio = new RecognitionAudio();
                recognitionAudio.setContent(base64EncodedData);

                try {
                    SyncRecognizeRequest request = new SyncRecognizeRequest();
                    request.setConfig(recognitionConfig);
                    request.setAudio(recognitionAudio);

                    SyncRecognizeResponse response = speechService.speech().syncrecognize(request).execute();
                    SpeechRecognitionResult result = response.getResults().get(0);
                    final String transcript = result.getAlternatives().get(0).getTranscript();

                    speechToTextResult.setText(transcript);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

            }

        });

    }

}

}

activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/speech_to_text_result"
    android:textSize="18dp"
    android:layout_alignParentTop="true"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:id="@+id/browse_button"
    android:text="Browse"/>

Abhi55Y commented 4 years ago

Logcat file 2020-06-15 21:52:08.677 7904-7904/? I/le.googlespeec: Late-enabling -Xcheck:jni 2020-06-15 21:52:08.757 7904-7904/? E/le.googlespeec: Unknown bits set in runtime_flags: 0x8000 2020-06-15 21:52:08.761 7904-7904/? I/le.googlespeec: Reinit property: dalvik.vm.checkjni= false 2020-06-15 21:52:08.788 7904-7904/? E/libc: Access denied finding property "runtime.mmitest.isrunning" 2020-06-15 21:52:08.793 7904-7904/? D/ActivityThread: Attach thread to application 2020-06-15 21:52:08.983 7904-7904/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::Init 2020-06-15 21:52:08.983 7904-7904/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::StartWatch 2020-06-15 21:52:08.983 7904-7904/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::WatchPackage: /data/hotpatch/fwkhotpatch/ 2020-06-15 21:52:08.983 7904-7904/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::CheckAndWatchPatch: /data/hotpatch/fwkhotpatch/com.example.googlespeech 2020-06-15 21:52:08.983 7904-7904/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::CheckAndWatchPatch: /data/hotpatch/fwkhotpatch/all 2020-06-15 21:52:08.983 7904-7904/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::Run 2020-06-15 21:52:08.986 7904-7963/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::Reading 2020-06-15 21:52:08.986 7904-7963/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::CheckNotifyEvent 2020-06-15 21:52:08.986 7904-7963/com.example.googlespeech I/le.googlespeec: QarthPatchMonintor::CheckNotifyEvent before read 2020-06-15 21:52:09.036 7904-7941/com.example.googlespeech I/HwApiCacheMangerEx: apicache path=/storage/emulated/0 state=mounted key=com.example.googlespeech#10336#256 2020-06-15 21:52:09.036 7904-7941/com.example.googlespeech I/HwApiCacheMangerEx: apicache path=/storage/0748-1500 state=mounted key=com.example.googlespeech#10336#256 2020-06-15 21:52:09.086 7904-7904/com.example.googlespeech V/ActivityThread: callActivityOnCreate 2020-06-15 21:52:09.095 7904-7941/com.example.googlespeech I/HwApiCacheMangerEx: apicache path=/storage/emulated/0 state=mounted key=com.example.googlespeech#10336#0 2020-06-15 21:52:09.095 7904-7941/com.example.googlespeech I/HwApiCacheMangerEx: apicache path=/storage/0748-1500 state=mounted key=com.example.googlespeech#10336#0 2020-06-15 21:52:09.102 7904-7941/com.example.googlespeech I/AwareBitmapCacher: init processName:com.example.googlespeech pid=7904 uid=10336 2020-06-15 21:52:09.124 7904-7904/com.example.googlespeech V/HwWidgetFactory: : successes to get AllImpl object and return.... 2020-06-15 21:52:09.125 7904-7979/com.example.googlespeech E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@9ee6965 2020-06-15 21:52:09.125 7904-7979/com.example.googlespeech E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@7bdd63a 2020-06-15 21:52:09.162 7904-7904/com.example.googlespeech I/OverScrollerOptimization: start init SmartSlideOverScroller and get the overscroller config 2020-06-15 21:52:09.163 7904-7904/com.example.googlespeech I/OverScrollerOptimization: get the overscroller config 2020-06-15 21:52:09.230 7904-7904/com.example.googlespeech W/le.googlespeec: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed) 2020-06-15 21:52:09.231 7904-7904/com.example.googlespeech W/le.googlespeec: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) 2020-06-15 21:52:09.273 7904-7904/com.example.googlespeech D/ActivityThread: add activity client record, r= ActivityRecord{bf294bb token=android.os.BinderProxy@4c2b68a {com.example.googlespeech/com.example.googlespeech.MainActivity}} token= android.os.BinderProxy@4c2b68a 2020-06-15 21:52:09.338 7904-7987/com.example.googlespeech D/HiTouch_PressGestureDetector: onAttached, package=com.example.googlespeech, windowType=1, mHiTouchRestricted=false 2020-06-15 21:52:09.356 7904-7964/com.example.googlespeech I/iGraphics: [0020080c] pn: com.example.googlespeech, p: 7904 2020-06-15 21:52:09.356 7904-7964/com.example.googlespeech I/iGraphics: [0030080c] no spt app: com.example.googlespeech 2020-06-15 21:52:09.380 7904-7964/com.example.googlespeech D/mali_winsys: EGLint new_window_surface(egl_winsys_display , void , EGLSurface, EGLConfig, egl_winsys_surface , EGLBoolean) returns 0x3000 2020-06-15 21:52:09.393 7904-7964/com.example.googlespeech W/Gralloc3: mapper 3.x is not supported 2020-06-15 21:52:09.548 7904-7904/com.example.googlespeech I/HwViewRootImpl: removeInvalidNode jank list is null 2020-06-15 21:52:12.986 7904-7904/com.example.googlespeech W/Settings: Setting device_provisioned has moved from android.provider.Settings.Secure to android.provider.Settings.Global. 2020-06-15 21:52:12.986 7904-7904/com.example.googlespeech V/HiTouch_HiTouchSensor: User setup is finished. 2020-06-15 21:52:13.019 7904-7904/com.example.googlespeech I/HwViewRootImpl: removeInvalidNode all the node in jank list is out of time 2020-06-15 21:52:13.088 7904-7904/com.example.googlespeech V/AudioManager: querySoundEffectsEnabled... 2020-06-15 21:52:13.092 7904-7904/com.example.googlespeech D/HwFrameworkSecurityPartsFactory: HwFrameworkSecurityPartsFactory in. 2020-06-15 21:52:13.092 7904-7904/com.example.googlespeech I/HwFrameworkSecurityPartsFactory: add HwFrameworkSecurityPartsFactory to memory. 2020-06-15 21:52:13.602 7904-7964/com.example.googlespeech W/libEGL: EGLNativeWindowType 0x79ebcf1e50 disconnect failed 2020-06-15 21:52:14.102 7904-7904/com.example.googlespeech D/AwareBitmapCacher: handleInit switch not opened pid=7904 2020-06-15 21:52:25.229 7904-7964/com.example.googlespeech D/mali_winsys: EGLint new_window_surface(egl_winsys_display , void , EGLSurface, EGLConfig, egl_winsys_surface , EGLBoolean) returns 0x3000 2020-06-15 21:52:25.251 7904-7904/com.example.googlespeech I/HwViewRootImpl: removeInvalidNode all the node in jank list is out of time 2020-06-15 21:52:25.316 7904-8155/com.example.googlespeech I/MediaPlayerNative: prepare MediaPlayer(0x79ebcef640) 2020-06-15 21:52:25.330 7904-7942/com.example.googlespeech D/MediaPlayerNative: Message: MEDIA_PREPARED(1), ext1=0, ext2=0x0 2020-06-15 21:52:25.330 7904-7942/com.example.googlespeech D/MediaPlayerNative: [notify] : [1170] callback app listenerNotNull=1, send=1 2020-06-15 21:52:25.330 7904-8155/com.example.googlespeech I/MediaPlayerNative: prepare complete - status=0 MediaPlayer(0x79ebcef640) 2020-06-15 21:52:25.333 7904-8155/com.example.googlespeech V/PlayerBase: baseStart() piid=2279 2020-06-15 21:52:25.336 7904-8155/com.example.googlespeech I/MediaPlayer: [HSM] stayAwake true uid: 10336, pid: 7904 2020-06-15 21:52:25.337 7904-8155/com.example.googlespeech D/MediaPlayerNative: Action:start, CurrentState:MEDIA_PLAYER_STARTED 2020-06-15 21:52:25.348 7904-8155/com.example.googlespeech W/AbstractGoogleClient: Application name is not set. Call Builder#setApplicationName. 2020-06-15 21:52:25.398 7904-8155/com.example.googlespeech D/NetworkSecurityConfig: No Network Security Config specified, using platform default 2020-06-15 21:52:25.436 7904-7942/com.example.googlespeech D/MediaPlayerNative: Message: Unknown MediaEventType(6), ext1=0, ext2=0x0 2020-06-15 21:52:25.436 7904-7942/com.example.googlespeech D/MediaPlayerNative: [notify] : [1170] callback app listenerNotNull=1, send=1 2020-06-15 21:52:25.519 7904-7942/com.example.googlespeech D/MediaPlayerNative: [notify] : [1170] callback app listenerNotNull=1, send=1 2020-06-15 21:52:28.400 7904-8155/com.example.googlespeech W/System.err: javax.net.ssl.SSLException: Write error: ssl=0x7980637e48: I/O error during system call, Broken pipe 2020-06-15 21:52:28.404 7904-8155/com.example.googlespeech W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_write(Native Method) 2020-06-15 21:52:28.404 7904-8155/com.example.googlespeech W/System.err: at com.android.org.conscrypt.NativeSsl.write(NativeSsl.java:426) 2020-06-15 21:52:28.404 7904-8155/com.example.googlespeech W/System.err: at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLOutputStream.write(ConscryptFileDescriptorSocket.java:626) 2020-06-15 21:52:28.404 7904-8155/com.example.googlespeech W/System.err: at com.android.okhttp.okio.Okio$1.write(Okio.java:78) 2020-06-15 21:52:28.404 7904-8155/com.example.googlespeech W/System.err: at com.android.okhttp.okio.AsyncTimeout$1.write(AsyncTimeout.java:157) 2020-06-15 21:52:28.404 7904-8155/com.example.googlespeech W/System.err: at com.android.okhttp.okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:177) 2020-06-15 21:52:28.404 7904-8155/com.example.googlespeech W/System.err: at com.android.okhttp.okio.RealBufferedSink.write(RealBufferedSink.java:47) 2020-06-15 21:52:28.404 7904-8155/com.example.googlespeech W/System.err: at com.android.okhttp.internal.http.Http1xStream$FixedLengthSink.write(Http1xStream.java:290) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at com.android.okhttp.okio.RealBufferedSink.close(RealBufferedSink.java:235) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at com.android.okhttp.okio.RealBufferedSink$1.close(RealBufferedSink.java:210) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:81) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at com.example.googlespeech.MainActivity$2.run(MainActivity.java:124) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at java.util.concurrent.ThreadPoolExecutor.processTask(ThreadPoolExecutor.java:1187) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 2020-06-15 21:52:28.405 7904-8155/com.example.googlespeech W/System.err: at java.lang.Thread.run(Thread.java:929) 2020-06-15 21:52:30.099 7904-7942/com.example.googlespeech D/MediaPlayerNative: Message: MEDIA_PLAYBACK_COMPLETE(2), ext1=0, ext2=0x0 2020-06-15 21:52:30.099 7904-7942/com.example.googlespeech D/MediaPlayerNative: [notify] : [1170] callback app listenerNotNull=1, send=1 2020-06-15 21:52:30.100 7904-7942/com.example.googlespeech D/MediaPlayerNative: [notify] : [1170] callback app listenerNotNull=1, send=1 2020-06-15 21:52:30.100 7904-7904/com.example.googlespeech V/PlayerBase: baseStop() piid=2279 2020-06-15 21:52:30.101 7904-7904/com.example.googlespeech V/PlayerBase: baseRelease() piid=2279 state=4 2020-06-15 21:52:30.102 7904-7904/com.example.googlespeech I/MediaPlayer: [HSM] stayAwake false uid: 10336, pid: 7904 2020-06-15 21:52:30.103 7904-7904/com.example.googlespeech V/MediaPlayer: resetDrmState: mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false 2020-06-15 21:52:30.104 7904-7904/com.example.googlespeech V/MediaPlayer: cleanDrmObj: mDrmObj=null mDrmSessionId=null 2020-06-15 21:52:30.124 7904-7904/com.example.googlespeech I/MediaPlayerNative: Pid:7904 MediaPlayer destructor MediaPlayer(0x79ebcef640) 2020-06-15 21:52:30.125 7904-7904/com.example.googlespeech I/MediaPlayer: [HSM] stayAwake false uid: 10336, pid: 7904 2020-06-15 21:52:30.127 7904-7904/com.example.googlespeech W/MediaPlayer: mediaplayer went away with unhandled events