Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/192.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何使用DialogFlow V2客户端库_Android_Dialogflow Es - Fatal编程技术网

Android 如何使用DialogFlow V2客户端库

Android 如何使用DialogFlow V2客户端库,android,dialogflow-es,Android,Dialogflow Es,我正在使用dialogflowV2,但现在已发布。所以我尝试使用 下面是我在Android中的代码 private String projectId = "modroid-test-3aedd"; private TextView textView; private SpeechToText toText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedIn

我正在使用dialogflowV2,但现在已发布。所以我尝试使用

下面是我在Android中的代码

 private String projectId = "modroid-test-3aedd";
 private TextView textView;
 private SpeechToText toText;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = findViewById(R.id.textview);
    toText = new SpeechToText(this, textView);

    try {
        GoogleCredentials credentials = GoogleCredentials.fromStream(getResources().getAssets().open("Test-9d8a744b520a.json"))
                .createScoped(newArrayList("https://www.googleapis.com/auth/compute"));
        credentials.toBuilder().build();

    } catch (IOException e) {
        e.printStackTrace();
    }
    textView = findViewById(R.id.textview);
    new MyAsync(projectId).execute();

}

 @Override
 protected void onStart() {
    super.onStart();
    toText.start();
 }

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    toText.start();
}

class MyAsync extends AsyncTask {
    private String projectId;

    MyAsync(String projectId) {
        this.projectId = projectId;
    }

    @Override
    protected Object doInBackground(Object[] objects) {
        try {

            detectIntentStream(projectId, null, "7fff90e6-3879-4ed5-ad85-058531b3002a", "en-US");

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    public void detectIntentStream(String projectId, String audioFilePath, String sessionId,
                                   String languageCode) throws Throwable {
        // Start bi-directional StreamingDetectIntent stream.
        final CountDownLatch notification = new CountDownLatch(1);
        final List<Throwable> responseThrowables = new ArrayList<>();
        final List<StreamingDetectIntentResponse> responses = new ArrayList<>();

        // Instantiates a client
        try (SessionsClient sessionsClient = SessionsClient.create()) { // on this line it throws exception to me
            // Set the session name using the sessionId (UUID) and projectID (my-project-id)
            SessionName session = SessionName.of(projectId, sessionId);
            System.out.println("Session Path: " + session.toString());

            // Note: hard coding audioEncoding and sampleRateHertz for simplicity.
            // Audio encoding of the audio content sent in the query request.
            AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16;
            int sampleRateHertz = 16000;

            // Instructs the speech recognizer how to process the audio content.
            InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder()
                    .setAudioEncoding(audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16
                    .setLanguageCode(languageCode) // languageCode = "en-US"
                    .setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000
                    .build();

            ApiStreamObserver<StreamingDetectIntentResponse> responseObserver =
                    new ApiStreamObserver<StreamingDetectIntentResponse>() {
                        @Override
                        public void onNext(StreamingDetectIntentResponse response) {
                            // Do something when receive a response
                            responses.add(response);
                        }

                        @Override
                        public void onError(Throwable t) {
                            // Add error-handling
                            responseThrowables.add(t);
                        }

                        @Override
                        public void onCompleted() {
                            // Do something when complete.
                            notification.countDown();
                        }
                    };

            // Performs the streaming detect intent callable request
            ApiStreamObserver<StreamingDetectIntentRequest> requestObserver =
                    sessionsClient.streamingDetectIntentCallable().bidiStreamingCall(responseObserver);

            // Build the query with the InputAudioConfig
            QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();

            try (FileInputStream audioStream = new FileInputStream(audioFilePath)) {
                // The first request contains the configuration
                StreamingDetectIntentRequest request = StreamingDetectIntentRequest.newBuilder()
                        .setSession(session.toString())
                        .setQueryInput(queryInput)
                        .build();

                // Make the first request
                requestObserver.onNext(request);

                // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality
                // you would split the user input by time.
                byte[] buffer = new byte[4096];
                int bytes;
                while ((bytes = audioStream.read(buffer)) != -1) {
                    requestObserver.onNext(
                            StreamingDetectIntentRequest.newBuilder()
                                    .setInputAudio(ByteString.copyFrom(buffer, 0, bytes))
                                    .build());
                }
            } catch (RuntimeException e) {
                // Cancel stream.
                requestObserver.onError(e);
            }
            // Half-close the stream.
            requestObserver.onCompleted();
            // Wait for the final response (without explicit timeout).
            notification.await();
            // Process errors/responses.
            if (!responseThrowables.isEmpty()) {
                throw responseThrowables.get(0);
            }
            if (responses.isEmpty()) {
                throw new RuntimeException("No response from Dialogflow.");
            }

            for (StreamingDetectIntentResponse response : responses) {
                if (response.hasRecognitionResult()) {
                    System.out.format(
                            "Intermediate transcript: '%s'\n", response.getRecognitionResult().getTranscript());
                }
            }

            // Display the last query result
            QueryResult queryResult = responses.get(responses.size() - 1).getQueryResult();
            System.out.println("====================");
            System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
            System.out.format("Detected Intent: %s (confidence: %f)\n",
                    queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
            System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());

            textView.setText(queryResult.getQueryText() + queryResult.getFulfillmentText());
        }
    }
}
但它不起作用,给了我一个例外

 try (SessionsClient sessionsClient = SessionsClient.create()) 

你在这上面找到什么了吗@费萨拉赫米德还没有。。。我仍然在使用旧的android库,这是你找到什么了吗@费萨拉赫米德还没有。。。我仍然在使用旧的android库,这是亲爱的Rahul,谢谢你给我时间。但请仔细阅读我的问题,这是针对android的。第二,永远不要分享你的证件谢谢!我知道你为安德里奥所做的一切,你已经做到了,所以我只想看看你是否能帮助我。亲爱的拉胡尔谢谢你给我时间。但请仔细阅读我的问题,这是针对android的。第二,永远不要分享你的证件谢谢!我知道你为安德烈所做的一切,你已经做到了,所以我只想看看你是否能帮助我。
GoogleCredentials credentials = GoogleCredentials.fromStream(getResources().getAssets().open("Modroid-Test-9d8a744b520a.json"))
            .createScoped(newArrayList("https://www.googleapis.com/auth/compute"));
    credentials.toBuilder().build();
 try (SessionsClient sessionsClient = SessionsClient.create()) 
// 1. read json by InputStream
    InputStream stream = context.getAssets().open("-----.json");
    GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
    String projectId = ((ServiceAccountCredentials)credentials).getProjectId();

// 2. build SessionSettings
    SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
    SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();

// 3. create SessionsClient
    SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)
texts.add("Hi");
String sessionId="3f46dfa4-5204-84f3-1488-5556f3d6b8a1";
String languageCode="en-US";
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("E:\\GoogleDialogFlow\\ChatBox\\Json.json"))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));

SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
SessionsClient sessionsClient = SessionsClient.create(sessionsSettings);
SessionName session = SessionName.of(projectId, sessionId);
com.google.cloud.dialogflow.v2.TextInput.Builder textInput = TextInput.newBuilder().setText("Hi").setLanguageCode(languageCode);
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
QueryResult queryResult = response.getQueryResult();
System.out.println("====================");
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());    
credentials.toBuilder().build();```


This source code is working on my window but when I am publishing it getting error on Linux server.So time they are saying update your guava-23.6 jar file but problem is still there. 
I am trying read my .json file from one path. I am not setting the environment variable on Linux , even my local machine.