将二进制响应(流)直接写入 Notes 文档中的 MIME

Writing a binary response (stream) directly to MIME in a Notes document

当我使用 Watson API 时,我正在使用 Text2Speech 服务从该服务获取音频流(文件)。我已经得到包含代码的文件,但我的 MIME 稍后不包含任何内容。我在下面调用此方法后保存文档。将字节内容直接流式传输到 MIME 的任何最佳实践将不胜感激。

public void getSpeechFromText(AveedoContext aveedoContext, Document doc, String fieldName, String text, String voiceName) {
    try {
        Session session = aveedoContext.getXspHelper().getSession();
        session.setConvertMIME(false);
        TextToSpeech service = new TextToSpeech();
        String username = watsonSettings.getTextToSpeechUsername();
        String password = watsonSettings.getTextToSpeechPassword();
        if (username.isEmpty() || password.isEmpty()) {
            throw new AveedoException("No credentials provided for service");
        }
        service.setUsernameAndPassword(username, password);
        MIMEEntity mime = doc.getMIMEEntity(fieldName);
        if (mime == null) {
            mime = doc.createMIMEEntity(fieldName);
        }

        // local proxy?
        if (!Util.isEmpty(customEndpoint)) {
            // service.setEndPoint(customEndpoint + "/speech/");
        }

        Voice voice = Voice.getByName(voiceName);
        AudioFormat audio = AudioFormat.WAV;

        System.out.println("Fieldname: " + fieldName + "SPEECH: " + text + ", Voice: " + voice.getName() + ", Format: "
                + audio.toString());

        InputStream stream = service.synthesize(text, voice, audio).execute();
        InputStream in = WaveUtils.reWriteWaveHeader(stream);

        Stream out = session.createStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer);
        }
        mime.setContentFromBytes(out, "audio/wav", MIMEEntity.ENC_IDENTITY_BINARY);
        out.close();            
        session.setConvertMIME(true);
        in.close();
        stream.close();

    } catch (Throwable e) {
        aveedoLogger.error("Error calling Watson service (text to speech)", e);
        e.printStackTrace();
    }
}

我认为您需要创建一个子 MIME 实体。我在我的一个应用程序中使用以下代码来附加图像:

boolean convertMime = JSFUtil.getSessionAsSigner().isConvertMime();
if (convertMime) {
    JSFUtil.getSessionAsSigner().setConvertMime(false);
}

final MIMEEntity body = doc.createMIMEEntity(getAttachmentFieldName());

// Add binary attachment
final MIMEEntity attachmentChild = body.createChildEntity();
final MIMEHeader bodyHeader = attachmentChild.createHeader("Content-Disposition");
bodyHeader.setHeaderVal("attachment; filename=" + incident.getPhoto().getName());
Stream imgStream = getPhoto(doc, incident.getPhoto());
attachmentChild.setContentFromBytes(imgStream, incident.getPhoto().getType(), MIMEEntity.ENC_IDENTITY_BINARY);
imgStream.close();
imgStream.recycle();
imgStream = null;

if (convertMime) {
    JSFUtil.getSessionAsSigner().setConvertMime(true);
}