Skip to content

Commit 75f6923

Browse files
committed
WIP: speech: add StreamingRecognizer helper
1 parent 9623994 commit 75f6923

1 file changed

Lines changed: 69 additions & 0 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* Copyright 2017, Google Inc. All rights reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.google.cloud.speech.spi.v1;
17+
18+
import com.google.api.gax.grpc.ApiStreamObserver;
19+
import com.google.cloud.speech.v1.StreamingRecognitionConfig;
20+
import com.google.cloud.speech.v1.StreamingRecognizeRequest;
21+
import com.google.cloud.speech.v1.StreamingRecognizeResponse;
22+
import com.google.protobuf.ByteString;
23+
import java.io.OutputStream;
24+
25+
public class StreamingRecognizer {
26+
public static OutputStream call(
27+
SpeechClient client,
28+
StreamingRecognitionConfig config,
29+
ApiStreamObserver<StreamingRecognizeResponse> responseObserver) {
30+
ApiStreamObserver<StreamingRecognizeRequest> requestObserver =
31+
client.streamingRecognizeCallable().bidiStreamingCall(responseObserver);
32+
requestObserver.onNext(
33+
StreamingRecognizeRequest.newBuilder().setStreamingConfig(config).build());
34+
return new StreamWriter(requestObserver);
35+
}
36+
37+
private static class StreamWriter extends OutputStream {
38+
private final ApiStreamObserver<StreamingRecognizeRequest> stream;
39+
40+
private StreamWriter(ApiStreamObserver<StreamingRecognizeRequest> stream) {
41+
this.stream = stream;
42+
}
43+
44+
@Override
45+
public void close() {
46+
stream.onCompleted();
47+
}
48+
49+
@Override
50+
public void write(byte[] b, int off, int len) {
51+
stream.onNext(
52+
StreamingRecognizeRequest.newBuilder()
53+
.setAudioContent(ByteString.copyFrom(b, off, len))
54+
.build());
55+
}
56+
57+
/**
58+
* This method exists to satisfy the abstract OutputStream class. However, it's probably slow
59+
* and should be avoided. If writing byte-by-byte is required, consider buffering the stream.
60+
*/
61+
@Override
62+
public void write(int b) {
63+
stream.onNext(
64+
StreamingRecognizeRequest.newBuilder()
65+
.setAudioContent(ByteString.copyFrom(new byte[] {(byte) (b & 0xFF)}))
66+
.build());
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)