This article introduces a detailed explanation of the Android voice broadcast implementation solution (no SDK) and shares it with you. The details are as follows:
Function description
Similar to the voice broadcast function when Alipay collects payment: When others scan your payment code, you will hear the voice broadcast of "Alipay is 12.55 yuan."
Problems to be solved
1. Play a single voice file
2. Play the next one immediately after playing a single voice file, so that it can be continuously
3. Processing when multiple complete voice sequences need to be broadcasted (for example, Alipay receives multiple payment pushes in a short time)
Implementation ideas
1. Select MediaPlayer for playing a single file
First create a MediaPlayer instance
MediaPlayer player = new MediaPlayer();
Then set the data source, where the data source is obtained from assets, of course, you can also place the voice file in the raw folder
fd = (path); ((), (), ());
Then call prepareAsync() method, load asynchronously, and set up listening, and start playing after loading (different from prepare method)
(); (new () { @Override public void onPrepared(MediaPlayer mp) { (); } });
2. Since there are more than one voice file to play, you need to monitor the playback status and play the next voice after the playback is completed.
(new () { @Override public void onCompletion(MediaPlayer mp) { (); counter[0]++; if (counter[0] < ()) { try { AssetFileDescriptor fileDescriptor = (("sound/tts_%s.mp3", (counter[0]))); ((), (), ()); (); } catch (IOException e) { (); (); } } else { (); (); } } });
3. Report requests multiple times in a short time, and use synchronization method to perform the next item. After one playback, synchronized + notifyAll() is used here to implement it. Of course, other methods can be used.
Code encapsulation
The function code is divided into two parts, part of which is a List composed of phonological sequences, here is VoiceTemplate;
Part of it is a functional package for playback, receiving a List, and then playing voice, which is called VoiceSpeaker;
See the end of the article for detailed code.
Code usage
For example, to play "Alipay's 12:13 Yuan" with the code as follows
final List<String> list = new VoiceTemplate() .prefix("success") .numString("12.13") .suffix("yuan") .gen(); ().speak(list);
Source code
KTools
/jiangkang/KTools/blob/master/app/src/main/java/com/jiangkang/ktools/audio/
/jiangkang/KTools/blob/master/app/src/main/java/com/jiangkang/ktools/audio/
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.