2017-02-28 101 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); 
    } 
}