亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解Android 語音播報實現(xiàn)方案(無SDK)

 更新時間:2017年11月29日 09:20:59   作者:姜康  
本篇文章主要介紹了詳解Android 語音播報實現(xiàn)方案(無SDK),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

本文介紹了詳解Android 語音播報實現(xiàn)方案(無SDK),分享給大家,具體如下:

功能描述

類似支付寶收款時候的語音播報功能:當(dāng)別人掃描你的收款碼,你收到錢之后,就會聽到“支付寶到賬12.55元”的語音播報。

要解決的問題

1.播放單個語音文件

2.播放完單個語音文件之后立即播放下一條,這樣才能連續(xù)

3.當(dāng)多個完整的語音序列都需要播報時的處理(比如支付寶短時間內(nèi)收到多條收款推送)

實現(xiàn)思路

1、播放單個文件選擇MediaPlayer

首先創(chuàng)建一個MediaPlayer實例

MediaPlayer player = new MediaPlayer();

然后設(shè)置數(shù)據(jù)源,這里數(shù)據(jù)源從assets中獲取,當(dāng)然也可以將語音文件放在raw文件夾里

 fd = FileUtils.getAssetFileDescription(path);
 player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(),
              fd.getLength());

然后調(diào)用prepareAsync()方法,異步加載,并設(shè)置監(jiān)聽,加載完畢之后開始播放(與prepare方法區(qū)別開來)

player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
              mp.start();
            }
          });

2、由于播放的語音文件不止一個,因此需要監(jiān)聽播放完成的狀態(tài),在播放完成之后播放下一條語音

 player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
              mp.reset();
              counter[0]++;
              if (counter[0] < list.size()) {
                try {
                  AssetFileDescriptor fileDescriptor = FileUtils.getAssetFileDescription(String.format("sound/tts_%s.mp3", list.get(counter[0])));
                  mp.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
                  mp.prepare();
                } catch (IOException e) {
                  e.printStackTrace();
                  latch.countDown();
                }
              } else {
                mp.release();
                latch.countDown();
              }
            }
          });

3、短時間多次播報請求,開采用同步方式進行,一條播完播放下一條,這里采用synchronized + notifyAll() 實現(xiàn),當(dāng)然也可以用別的方法。

代碼封裝

功能代碼分為兩部分,一部分是語音序列組成的List,這里是VoiceTemplate;

一部分是播放的功能封裝,接收List,然后播放語音,這里叫做VoiceSpeaker;

詳細代碼見文末。

代碼使用

比如要播放“支付寶到賬十二點一三元”,代碼如下

final List<String> list = new VoiceTemplate()
        .prefix("success")
        .numString("12.13")
        .suffix("yuan")
        .gen();

VoiceSpeaker.getInstance().speak(list);

源碼

KTools

https://github.com/jiangkang/KTools/blob/master/app/src/main/java/com/jiangkang/ktools/audio/VoiceSpeaker.java

https://github.com/jiangkang/KTools/blob/master/app/src/main/java/com/jiangkang/ktools/audio/VoiceTemplate.java

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論