2017-02-28 147 views
-2

就像我们想在android应用程序中播放音频文件一样,我们使用媒体播放器并从原始文件夹中获取音频文件,然后我们只需播放它。我想要做的就像我想从字符串数据播放音频。例如: String value =“Hello sir”;播放字符串数据。 (播放字符串值为音频)

我想播放这个字符串“你好,先生”作为音频。

+0

搜索 “文字转语音” –

+0

@SergeyGlotov感谢 –

回答

0

您可以使用TextToSpeech

public class MainActivity extends AppCompatActivity { 

    private TextToSpeech mTextToSpeech; 

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

     mTextToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { 
      @Override 
      public void onInit(int status) { 
       if (status != TextToSpeech.ERROR) { 
        mTextToSpeech.setLanguage(Locale.UK); 
        speak("Hello sir"); 
       } 
      } 
     }); 
    } 

    private void speak(String text) { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      textToSpeechGreater21(text); 
     } else { 
      textToSpeechUnder20(text); 
     } 
    } 

    @SuppressWarnings("deprecation") 
    private void textToSpeechUnder20(String text) { 
     HashMap<String, String> map = new HashMap<>(); 
     map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId"); 
     mTextToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, map); 
    } 

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
    private void textToSpeechGreater21(String text) { 
     String utteranceId = this.hashCode() + ""; 
     mTextToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId); 
    } 
}