2016-12-15 70 views
2

當我玩弄Watson API時,我使用Text2Speech服務從服務中獲取音頻流(文件)。我已經用代碼獲得了該文件,但是我的MIME稍後不包含任何內容。我在下面調用此方法後保存文檔。任何將字節內容直接傳輸到MIME的最佳實踐將不勝感激。將二進制響應(流)直接寫入Notes文檔中的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(); 
    } 
} 
+0

你嘗試添加'out.setPosition(0)'嗎? – stwissel

+0

嘗試過但沒有區別 –

+0

這是做什麼或換句話說:當我不使用它時有什麼不同? –

回答

2

我相信你需要創建一個子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); 
} 
+0

我試過這個,但是即使這個字段沒有在文檔中創建 –

+0

啊等等......如果我立即保存它,那麼該字段就在那裏。之後無法使用單獨的保存操作將其保存。 –