【问题标题】:Play String data. (Play string value as audio)播放字符串数据。 (将字符串值作为音频播放)
【发布时间】:2017-02-28 11:43:58
【问题描述】:

当我们想在android应用程序中播放音频文件时,我们使用媒体播放器并从原始文件夹中获取音频文件,我们只需播放它。我想做的就像我想从字符串数据中播放音频。例子 : 字符串值 = "你好先生";

我想将这个字符串“hello sir”作为音频播放。

【问题讨论】:

  • 搜索“TextToSpeech”
  • @SergeyGlotov 谢谢

标签: android android-mediaplayer avaudioplayer


【解决方案1】:

你可以使用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);
    }
}

【讨论】:

    猜你喜欢
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    相关资源
    最近更新 更多