无法调用SpeechClient.recognize(RecognizeRequest请求):抛出异常

时间:2017-11-02 22:40:22

标签: android exception speech-recognition google-speech-api

这是我第一次发帖,所以我对规则不太熟悉,但是这里有。 我一直试图让Google Cloud Speech API在Android上运行,但无济于事。相同的代码在Java上运行得很好,但在Android上却不行。 我的代码运行正常,直到我使用语音客户端调用识别方法。 这是错误:

11-02 18:38:03.922 6959-6982/capstone.speechrecognitionsimple E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: capstone.speechrecognitionsimple, PID: 6959
java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:304)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
 Caused by: com.google.common.util.concurrent.ExecutionError: java.lang.AbstractMethodError: abstract method "java.util.concurrent.ScheduledExecutorService io.grpc.internal.ClientTransportFactory.getScheduledExecutorService()"
    at com.google.common.util.concurrent.Futures.wrapAndThrowUnchecked(Futures.java:1319)
    at com.google.common.util.concurrent.Futures.getUnchecked(Futures.java:1311)
    at com.google.api.gax.rpc.ApiExceptions.callAndTranslateApiException(ApiExceptions.java:53)
    at com.google.api.gax.rpc.UnaryCallable.call(UnaryCallable.java:114)
    at com.google.cloud.speech.v1.SpeechClient.recognize(SpeechClient.java:245)
    at capstone.speechrecognitionsimple.MainActivity$InitTask.doInBackground(MainActivity.java:94)
    at capstone.speechrecognitionsimple.MainActivity$InitTask.doInBackground(MainActivity.java:38)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
    at java.lang.Thread.run(Thread.java:818) 
 Caused by: java.lang.AbstractMethodError: abstract method "java.util.concurrent.ScheduledExecutorService io.grpc.internal.ClientTransportFactory.getScheduledExecutorService()"
    at io.grpc.internal.CallCredentialsApplyingTransportFactory.getScheduledExecutorService(CallCredentialsApplyingTransportFactory.java:52)
    at io.grpc.internal.ManagedChannelImpl$RealChannel.newCall(ManagedChannelImpl.java:557)
    at com.google.api.gax.grpc.GrpcHeaderInterceptor.interceptCall(GrpcHeaderInterceptor.java:59)
    at io.grpc.ClientInterceptors$InterceptorChannel.newCall(ClientInterceptors.java:104)
    at io.grpc.internal.ManagedChannelImpl.newCall(ManagedChannelImpl.java:536)
    at com.google.api.gax.grpc.GrpcDirectCallable.newCall(GrpcDirectCallable.java:76)
    at com.google.api.gax.grpc.GrpcDirectCallable.futureCall(GrpcDirectCallable.java:70)
    at com.google.api.gax.grpc.GrpcExceptionCallable.futureCall(GrpcExceptionCallable.java:65)
    at com.google.api.gax.grpc.GrpcAttemptCallable.call(GrpcAttemptCallable.java:80)
    at com.google.api.gax.grpc.GrpcRetryingCallable.futureCall(GrpcRetryingCallable.java:64)
    at com.google.api.gax.grpc.GrpcRetryingCallable.futureCall(GrpcRetryingCallable.java:46)
    at com.google.api.gax.rpc.EntryPointUnaryCallable.futureCall(EntryPointUnaryCallable.java:70)
    at com.google.api.gax.rpc.UnaryCallable.futureCall(UnaryCallable.java:89)
    at com.google.api.gax.rpc.UnaryCallable.call(UnaryCallable.java:114) 
    at com.google.cloud.speech.v1.SpeechClient.recognize(SpeechClient.java:245) 
    at capstone.speechrecognitionsimple.MainActivity$InitTask.doInBackground(MainActivity.java:94) 
    at capstone.speechrecognitionsimple.MainActivity$InitTask.doInBackground(MainActivity.java:38) 
    at android.os.AsyncTask$2.call(AsyncTask.java:292) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
    at java.lang.Thread.run(Thread.java:818) 

我不知道为什么会这样。这是我的代码:

package capstone.speechrecognitionsimple;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.speech.v1.RecognitionAudio;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.RecognizeRequest;
import com.google.cloud.speech.v1.RecognizeResponse;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.SpeechRecognitionResult;
import com.google.cloud.speech.v1.SpeechSettings;
import com.google.protobuf.ByteString;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.util.List;

public class MainActivity extends AppCompatActivity {

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

        InitTask init = new InitTask();
        init.execute();

    }


    class InitTask extends AsyncTask<ByteString, Void, String> {
        SpeechClient speechClient = null;
        protected String doInBackground(ByteString... strings) {
            String transcript = "Transcript:\n";
            try {
                Log.i("InitTask", "Creating client...");

                InputStream credentialsStream = getAssets().open("credentials.json");
                GoogleCredentials credentials = GoogleCredentials.fromStream(credentialsStream);
                FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(credentials);

                InputStream path = getAssets().open("audio.raw");
                byte[] data = IOUtils.toByteArray(path);
                ByteString audioBytes = ByteString.copyFrom(data);

                SpeechSettings speechSettings =
                        SpeechSettings.newBuilder()
                                .setCredentialsProvider(credentialsProvider)
                                .build();

                Log.i("InitTask", "Settings Created");

                speechClient = SpeechClient.create(speechSettings);

                Log.i("InitTask", "Client Created");

                RecognitionConfig.AudioEncoding encoding = RecognitionConfig.AudioEncoding.LINEAR16;
                Log.i("InitTask", "Encoding Created");

                int sampleRateHertz = 16000;
                String languageCode = "en-US";
                RecognitionConfig config = RecognitionConfig.newBuilder()
                        .setEncoding(encoding)
                        .setSampleRateHertz(sampleRateHertz)
                        .setLanguageCode(languageCode)
                        .build();

                Log.i("finalRec", "Config Created");

                RecognitionAudio audio = RecognitionAudio.newBuilder()
                        .setContent(audioBytes)
                        .build();
                Log.i("finalRec", "Audio Created");
                RecognizeRequest request = RecognizeRequest.newBuilder()
                        .setConfig(config)
                        .setAudio(audio)
                        .build();

                RecognizeResponse response = speechClient.recognize(request);
                Log.i("finalRec", "Called RECOGNIZE");


                List<SpeechRecognitionResult> results = response.getResultsList();

                for (SpeechRecognitionResult result : results) {
                    List<SpeechRecognitionAlternative> alternatives = result.getAlternativesList();
                    for (SpeechRecognitionAlternative alternative : alternatives) {
                        transcript+= alternative.getTranscript();
                    }
                }
            }
            catch(Exception e){
                Log.e("Client", "" + e.toString());
                e.printStackTrace();
            }
            try {
                speechClient.close();
            }  catch (Exception e) {
                Log.e("Client", "" + e.toString());
                e.printStackTrace();
            }
            return transcript;
        }

        protected void onPostExecute(String transcript) {
            Log.i("Transcript", "" +transcript);
        }
    }
}

最后,这是我的gradle构建文件:

apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'

ext {
    grpcVersion = '1.4.0'
}
android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "capstone.speechrecognitionsimple"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

        javaCompileOptions{
            annotationProcessorOptions{
                includeCompileClasspath = true
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.2'
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/INDEX.LIST'
        exclude 'META-INF/io.netty.versions.properties'
        exclude 'META-INF/io.grpc.ManagedChannelProvider'
        exclude 'META-INF/services/io.grpc.ManagedChannelProvider'
        exclude 'project.properties'
        pickFirst 'META-INF/license.txt'
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.3.0'
    }
    plugins {
        javalite {
            artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
        }
        grpc {
            artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}"
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.plugins {
                javalite {}
                grpc {
                    // Options added to --grpc_out
                    option 'lite'
                }
            }
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    provided 'com.jakewharton.auto.value:auto-value-annotations:1.4'
    annotationProcessor 'com.google.auto.value:auto-value:1.4.1'

    // gRPC
    compile "io.grpc:grpc-okhttp:$grpcVersion"
    compile "io.grpc:grpc-protobuf-lite:$grpcVersion"
    compile "io.grpc:grpc-stub:$grpcVersion"
    compile 'javax.annotation:javax.annotation-api:1.2'
    protobuf 'com.google.protobuf:protobuf-java:3.3.1'

    compile group: 'com.google.api.grpc', name: 'grpc-google-cloud-speech-v1', version: '0.1.13'
    compile group: 'com.google.cloud', name: 'google-cloud-speech', version: '0.26.0-alpha'

    // OAuth2 for Google API
    compile('com.google.auth:google-auth-library-oauth2-http:0.7.0') {
        exclude module: 'httpclient'
    }

    compile 'com.android.support:multidex:1.0.0'

}

1 个答案:

答案 0 :(得分:1)

我在Protobuf中遇到了同样的问题。对于遇到此问题的其他人,请确保您在顶级build.gradle中具有以下内容:

classpath'com.google.protobuf:protobuf-gradle-plugin:0.8.6'