├── .gitignore
├── CONTRIBUTORS.md
├── LICENSE
├── README.md
├── _config.yml
├── amazon
└── index.js
├── amazon_speech.js
├── helper
└── index.js
├── index.js
├── package.json
└── test
├── amazon_speech_test.js
└── speech_test.js
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | .DS_STORE
3 | *.log
4 | *.zip
5 | node_modules/
6 |
--------------------------------------------------------------------------------
/CONTRIBUTORS.md:
--------------------------------------------------------------------------------
1 | ## Contributors
2 | - Mandy Chan - The Repo Owner and Main Contributor
3 |
4 | ## How to contribute?
5 | If you want to contribute to the project, please make sure your code has the following:
6 |
7 | - The functions are documented
8 | - Parameters are validated
9 | - Unit Tests for positive and negative cases are covered
10 | - And you provide documentation of new features; only if the feature is new.
11 |
12 | ## Contributing A Patch
13 |
14 | 1. Submit an issue describing your proposed change to the repo in question.
15 | 1. The repo owner will respond to your issue promptly.
16 | 1. Fork the desired repo, develop and test your code changes.
17 | 1. Ensure that your code adheres to the existing style
18 | 1. Ensure that your code has an appropriate set of unit tests which all pass.
19 | 1. Submit a pull request.
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ssml-builder
2 | This package creates Speech Synthesis Markup Language (SSML) using the builder pattern.
3 |
4 |
5 | Tired of creating SSML using string concatenation or worring about special characters like '&' ? This project aims to eliminate all these headaches by providing a clean and easy to use API. In addition to making SSML easier to create, this library is fully unit-tested to ensure things work as expected.
6 |
7 | Whether you're building an Amazon Alexa Skill using the older version of the JavaScript SDK or the new one, this library is compatible. See the examples in the lower portion of this documentation.
8 |
9 | ## Installation
10 | ```sh
11 | npm install ssml-builder --save
12 | ```
13 | ## Features
14 | * Works with both the new and old Alexa SDKs.
15 | * Handles special characters to ensure the SSML is well-formated.
16 | * This library supports the following SSML tags
17 | * amazon:effect
18 | * audio
19 | * break
20 | * emphasis
21 | * prosody
22 | * p
23 | * s
24 | * phoneme
25 | * speak
26 | * say-as which supports all of the known interpret-as values and formats. For more information, see [Amazon Documentation here](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#say-as)
27 | * characters
28 | * spell-out
29 | * cardinal
30 | * number
31 | * ordinal
32 | * digits
33 | * fraction
34 | * unit
35 | * date
36 | * time
37 | * telephone
38 | * address
39 | * interjection
40 | * expletive
41 | * sub
42 | * w
43 | * ivona:VB: Interpret the word as a verb (present simple).
44 | * ivona:VBD: Interpret the word as a past participle.
45 | * ivona:NN: Interpret the word as a noun.
46 | * ivona:SENSE_1: for more information, see [Amazon Documentation here](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#w)
47 |
48 |
49 | ## Code Example for the new Alexa SDK
50 | #### see link to the new Alexa SDK https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs
51 |
52 | ```javascript
53 | var Speech = require('ssml-builder');
54 |
55 | var speech = new Speech();
56 | speech.say('Hello')
57 | .pause('1s')
58 | .say('fellow Alexa developers')
59 | .pause('500ms')
60 | .say('Testing phone numbers')
61 | .sayAs({
62 | word: "+1-377-777-1888",
63 | interpret: "telephone"
64 | });
65 | var speechOutput = speech.ssml(true);
66 | this.emit(':tell', speechOutput);
67 | ```
68 |
69 | ## The above code will produce the following SSML
70 | > Note: In this example, the SSML is not surrounded by <speak/> because we passed 'true' into the ssml(boolean) method. This is intentional to work with the new SDK due to their current design.
71 | ```xml
72 | 'Hello fellow Alexa developers Testing phone numbers +1-377-777-1888'
73 | ```
74 |
75 | ## Code Example for the old Alexa SDK
76 | ```javascript
77 | var Speech = require('ssml-builder');
78 |
79 | var speech = new Speech();
80 | speech.say('Hello')
81 | .pause('1s')
82 | .say('fellow Alexa developers');
83 | var speechOutput = speech.toObject();
84 | response.tell(speechOutput);
85 | ```
86 |
87 | ## The above code will produce the following object
88 | ```json
89 | {
90 | "type": "SSML",
91 | "speech": "Hello fellow Alexa developers"
92 | }
93 | ```
94 | ## Amazon SSML specific tags
95 | When using Amazon specific tags, like whisper, you will need to import and use the AmazonSpeech object directly.
96 |
97 | ```javascript
98 | var AmazonSpeech = require('ssml-builder/amazon_speech');
99 |
100 | var speech = new AmazonSpeech();
101 | speech.say('Hello')
102 | .pause('1s')
103 | .whisper('I can see you when you are sleeping')
104 | .pause('500ms')
105 | .say('Is your phone number still')
106 | .sayAs({
107 | word: "+1-377-777-1888",
108 | interpret: "telephone"
109 | });
110 | var ssml = speech.ssml();
111 | ```
112 |
113 | ## Tag Examples
114 |
115 | #### [amazon:effect](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#amazon-effect)
116 | ```javascript
117 | speech.whisper('I can see you when you are sleeping');
118 | ```
119 |
120 | #### [audio](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#audio)
121 | ```javascript
122 | speech.audio('https://carfu.com/audio/carfu-welcome.mp3');
123 | ```
124 |
125 | #### [break](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#break)
126 | ```javascript
127 | speech.pause('500ms')
128 | .say('you hear this after a 500 millisecond pause')
129 | .pause('2s')
130 | .say('you heard this after a 2 second pause');
131 | ```
132 |
133 | #### [emphasis](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#emphasis)
134 | ```javascript
135 | speech.emphasis('strong', 'phrase will be strong');
136 | speech.emphasis('moderate', 'phrase will be moderate');
137 | speech.emphasis('reduced', 'phrase will be reduced');
138 | ```
139 |
140 | #### [prosody](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#prosody)
141 | ```javascript
142 | speech.prosody({rate: 'slow'}, 'say slow');
143 | speech.prosody({rate: 'fast'}, 'say fast');
144 | speech.prosody({rate: '120%'}, 'increase the rate of speech by 20%');
145 | speech.prosody({rate: '35%'}, 'decrease the rate of speech by 35%');
146 | speech.prosody({pitch: 'medium'}, 'set pitch to medium');
147 | speech.prosody({pitch: 'x-high'}, 'set pitch to extra high');
148 | speech.prosody({pitch: '+20%'}, 'increase the pitch by 20%');
149 | speech.prosody({pitch: '-10%'}, 'decrease the pitch by 10%');
150 | speech.prosody({volume: 'soft'}, 'set volume to soft');
151 | speech.prosody({volume: 'loud'}, 'set volume to loud');
152 | speech.prosody({volume: '+2db'}, 'increase volume by 2db');
153 | speech.prosody({volume: '-3db'}, 'decrease volume by 3db');
154 | ```
155 |
156 | #### [p](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#p)
157 | ```javascript
158 | speech.paragraph('phrase will be said with extra strong breaks before and after itself');
159 | ```
160 |
161 | #### [s](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#s)
162 | ```javascript
163 | speech.sentence('phrase will be said with strong breaks before and after itself');
164 | ```
165 |
166 | #### [phoneme](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#phoneme)
167 | ```javascript
168 | speech.phoneme('ipa', "pɪˈkɑːn", 'pecan');
169 | speech.phoneme('x-sampa', "fr\oU.z@n", 'frozen');
170 | ```
171 |
172 | #### [speak](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#speak)
173 | ```javascript
174 | speech.say('this will be said');
175 | ```
176 |
177 | #### [say-as](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#say-as)
178 | ```javascript
179 | speech.sayAs({word: '12345', interpret: 'digits'});
180 | speech.sayAs({word: 'usa', interpret: 'characters'});
181 | speech.sayAs({word: '5553329939', interpret: 'telephone'});
182 | ```
183 |
184 | #### [sub](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#sub)
185 | ```javascript
186 | speech.sub('magnesium', 'Mg');
187 | ```
188 |
189 | #### [w](https://developer.amazon.com/docs/custom-skills/speech-synthesis-markup-language-ssml-reference.html#w)
190 | ```javascript
191 | speech.partOfSpeech({word: 'record', role: 'amazon:VB'});
192 | speech.partOfSpeech({word: 'record', role: 'amazon:NN'});
193 | ```
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-architect
--------------------------------------------------------------------------------
/amazon/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | module.exports = require('../amazon_speech');
4 |
--------------------------------------------------------------------------------
/amazon_speech.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var Speech = require("./index.js");
4 | var AmazonSpeech = function () {
5 | this._elements = [];
6 | };
7 |
8 | AmazonSpeech.prototype = Object.create(Speech.prototype);
9 |
10 | AmazonSpeech.prototype.whisper = function (words) {
11 | this._notEmpty(words,"The words provided to AmazonSpeech#whisper(..) was '" + words + "'");
12 | var escapedWords = this._escape(words);
13 | this._elements.push("" + escapedWords + "");
14 | return this;
15 | };
16 |
17 | module.exports = AmazonSpeech;
18 |
--------------------------------------------------------------------------------
/helper/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * This helper class has a bunch of utility methods
5 | * @constructor
6 | */
7 | function Helper() {
8 | }
9 |
10 | /**
11 | * This method will give you a random word or phrase
12 | * @param words - an array of words or phrases
13 | * @returns {*} a random word or phrase
14 | */
15 | Helper.prototype.chooseRandomWord = function (words) {
16 | if (!Array.isArray(words)) {
17 | throw new Error('The words must be an array');
18 | }
19 | var index = this.random(words.length);
20 | return words[index];
21 | };
22 |
23 | /**
24 | * This method will give you a random index that is between 0 to max-1.
25 | * @param max is the max number that the result will never equal to or exceed.
26 | * @returns {number}
27 | */
28 | Helper.prototype.random = function (max) {
29 | return Math.floor(Math.random() * max);
30 | };
31 |
32 | module.exports = Helper;
33 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Helper = require('./helper');
4 |
5 | /**
6 | * This class helps simplify using SSML (Speech Synthesis Markup Language).
7 | * This only supports a subset of SSML tags which the Alexa device supports.
8 | * An example of how to use this class.
9 | *
10 | * var speech = new Speech();
11 | * speech.say("Let's begin your lesson");
12 | * speech.pause("1s");
13 | *
14 | *
15 | * Implement a method for , , All done
16 | * interpret-as="cardinal|ordinal|digits|fraction|unit|date|time|telephone|address" + format="mdy|dmy|ymd|md|dm|ym|my|d|m|y" All done
17 | * @constructor
18 | */
19 | function Speech() {
20 | this._elements = [];
21 | this._helper = new Helper();
22 | }
23 |
24 | /**
25 | * This appends raw text into the tag.
26 | * @param saying The raw text to insert into the speak tag.
27 | * @returns {Speech}
28 | */
29 | Speech.prototype.say = function (saying) {
30 | this._present(saying, "The saying provided to Speech#saying(..) was null or undefined.");
31 | this._elements.push(this._escape(saying));
32 | return this;
33 | };
34 |
35 | /**
36 | * Creates and inserts a paragraph tag.
37 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#p
38 | * @param paragraph The paragraph of text to insert.
39 | * @returns {Speech}
40 | */
41 | Speech.prototype.paragraph = function (paragraph) {
42 | this._present(paragraph, "The paragraph provided to Speech#paragraph(..) was null or undefined.");
43 | this._elements.push("
" + this._escape(paragraph) + "
");
44 | return this;
45 | };
46 |
47 | /**
48 | * Creates and inserts a sentence tag.
49 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#s
50 | * @param saying The sentence to insert.
51 | * @returns {Speech}
52 | */
53 | Speech.prototype.sentence = function (saying) {
54 | this._present(saying, "The sentence provided to Speech#sentence(..) was null or undefined.");
55 | this._elements.push("" + this._escape(saying) + "");
56 | return this;
57 | };
58 |
59 | /**
60 | * Creates and inserts a break tag. This method will also validate the break time conforms to the restrictions to Amazon Alexa.
61 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#break
62 | * @param duration the duration represented by a number + either 's' for second or 'ms' for milliseconds.
63 | * @returns {Speech}
64 | */
65 | Speech.prototype.pause = function (duration) {
66 | this._present(duration, "The duration provided to Speech#pause(..) was null or undefined.");
67 | this._validateDuration(duration);
68 | this._elements.push("");
69 | return this;
70 | };
71 |
72 | /**
73 | * Creates a break tag that will pause the audio based upon the strength provided.
74 | * For more information, please see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#break
75 | * @param strength such as none, x-weak, weak, medium, strong, x-strong
76 | * @returns {Speech}
77 | */
78 | Speech.prototype.pauseByStrength = function (strength) {
79 | this._present(strength, "The strength provided to Speech#pauseByStrength(..) was null or undefined");
80 | strength = strength.toLowerCase().trim();
81 | var strengths = ['none', 'x-weak', 'weak', 'medium', 'strong', 'x-strong'];
82 | isInList(strength, strengths, "The strength provided to Speech#pauseByStrength(..) was not valid. Received strength: " + strength);
83 |
84 | this._elements.push("");
85 | return this;
86 | };
87 |
88 | /**
89 | * Creates and inserts an audio tag.
90 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#audio
91 | * @param url a link to an audio file to play.
92 | * @param callback - an optional callback which is called to build the nested SSML
93 | * for the audio tag. The callback takes a single parameter of type
94 | * Speech.
95 | * @returns {Speech}
96 | */
97 | Speech.prototype.audio = function (url, callback) {
98 | this._present(url, "The url provided to Speech#audio(..) was null or undefined.");
99 | if (callback) {
100 | this._isFunction(callback, "callback");
101 | var audioBuilder = new Speech();
102 | callback(audioBuilder);
103 | this._elements.push("");
104 | } else {
105 | this._elements.push("");
106 | }
107 | return this;
108 | };
109 |
110 |
111 | /**
112 | * Creates and inserts a say-as tag.
113 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#say-as
114 | * @param word word or text to insert
115 | * @returns {Speech}
116 | */
117 | Speech.prototype.spell = function (word) {
118 | this._present(word, "The word provided to Speech#spell(..) was null or undefined.");
119 | this._elements.push("" + this._escape(word) + "");
120 | return this;
121 | };
122 |
123 | /**
124 | * Creates and inserts a say-as tag.
125 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#say-as
126 | * @param word word or text to insert , delay the delay represented by a number + either 's' for second or 'ms' for milliseconds.
127 | * @returns {Speech}
128 | */
129 | Speech.prototype.spellSlowly = function (word, delay) {
130 | this._present(word, "The word provided to Speech#spellSlowly(..) was null or undefined.");
131 | for (var i = 0; i < word.length; i++) {
132 | this._elements.push("" + this._escape(word.charAt(i)) + "");
133 | this.pause(delay);
134 | }
135 | return this;
136 | };
137 |
138 | /**
139 | * This constructs an object that the AlexaSkill.js accepts to send to the user.
140 | * @returns {{type: string, speech}}
141 | */
142 | Speech.prototype.toObject = function () {
143 | return {
144 | type: 'SSML',
145 | speech: this.ssml()
146 | }
147 | };
148 |
149 | /**
150 | * This method will construct an SSML xml string.
151 | * @param excludeSpeakTag when true, no root tag is provided; otherwise,
152 | * the content is surrounded by the , default is false
153 | * @returns {string} An XML string.
154 | */
155 | Speech.prototype.ssml = function (excludeSpeakTag) {
156 | if (excludeSpeakTag) {
157 | return this._elements.join(" ");
158 | }
159 | return "" + this._elements.join(" ") + "";
160 | };
161 |
162 | /**
163 | * Validates that the provided value is not null or undefined. It will throw an exception if it's either.
164 | * @param value The value to check.
165 | * @param msg The error message stating that exception.
166 | * @private
167 | */
168 | Speech.prototype._present = function (value, msg) {
169 | if (value === null || value === undefined) {
170 | throw msg;
171 | }
172 | };
173 |
174 | /**
175 | * This validates that a duration is in the correct format and doesn't exceed the
176 | * maximum duration of 10 seconds or 10000 milliseconds.
177 | *
178 | * The expected format is a positive number followed by 's' for second or 'ms' for milliseconds.
179 | *
180 | * @param duration The duration of a pause.
181 | * @throws an exception when the duration doesn't conform to the proper format or duration length.
182 | * @private
183 | */
184 | Speech.prototype._validateDuration = function (duration) {
185 | var re = /^(\d*\.?\d+)(s|ms)$/;
186 | if (duration.match(re)) {
187 | var parts = re.exec(duration);
188 | var pauseDuration = parts[1];
189 | var pauseType = parts[2];
190 | if (pauseType.toLowerCase() === 's' && pauseDuration > 10) {
191 | throw "The pause duration exceeds the allowed 10 second duration. Duration provided: " + duration;
192 | } else if (pauseDuration > 10000) {
193 | throw "The pause duration exceeds the allowed 10,000 milliseconds duration. Duration provided: " + duration;
194 | }
195 | } else {
196 | throw "The duration must be a number followed by either 's' for second or 'ms' for milliseconds. e.g., 10s or 100ms. Max duration is 10 seconds (10000 milliseconds)."
197 | }
198 | };
199 |
200 | /**
201 | * Creates and inserts a say-as tag that has multiple attributes such as interpret-as and format
202 | * interpret-as="characters|spell-out|cardinal|number|ordinal|digits|fraction|unit|date|time|telephone|address|interjection|expletive" + format="mdy|dmy|ymd|md|dm|ym|my|d|m|y"
203 | *
204 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#say-as
205 | * @param options an object that has three properties: word, interpret and format
206 | * word being the text to insert, interpret represents the attribute interpret-as and format represents the attribute format
207 | * @returns {Speech}
208 | */
209 | Speech.prototype.sayAs = function (options) {
210 | this._present(options, "The object provided to Speech#sayAs(..) was invalid.");
211 | this._present(options.word, "The word provided to Speech#sayAs(..) was null or undefined.");
212 | if (options.interpret) {
213 | var listOfInterpret = ['characters', 'spell-out', 'cardinal', 'number', 'ordinal', 'digits', 'fraction', 'unit', 'date', 'time', 'telephone', 'address', 'interjection', 'expletive'];
214 | isInList(options.interpret, listOfInterpret, "The interpret is invalid. Received this: " + options.interpret);
215 | if (options.format) {
216 | this._elements.push("" + options.word + "");
217 | return this;
218 | }
219 | this._elements.push("" + options.word + "");
220 | return this;
221 | } else {
222 | this._elements.push(options.word);
223 | return this;
224 | }
225 | };
226 |
227 | /**
228 | * Creates and inserts a w tag that customizes the pronunciation of words by specifying the word’s part of speech
229 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#w
230 | * @param options an object that has two properties: word and role
231 | * word being the text to insert and role represents the part of speech
232 | * @returns {Speech}
233 | */
234 | Speech.prototype.partOfSpeech = function (options) {
235 | this._present(options, "The object provided to Speech#partOfSpeech(..) was invalid.");
236 | this._present(options.word, "The word provided to Speech#partOfSpeech(..) was null or undefined.");
237 | var word = this._escape(options.word);
238 | if (options.role) {
239 | this._elements.push("" + word + "")
240 | }
241 | return this;
242 | };
243 |
244 | /**
245 | * Creates and inserts a phoneme tag.
246 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#phoneme
247 | * @param alphabet, ph, word
248 | * alphabet i.e "ipa"
249 | * ph i.e "pɪˈkɑːn"
250 | * word being the text to insert
251 | * @returns {Speech}
252 | */
253 | Speech.prototype.phoneme = function (alphabet, ph, word) {
254 | this._present(alphabet, "The alphabet provided to Speech#phoneme(..) was null or undefined.");
255 | this._present(ph, "The ph provided to Speech#phoneme(..) was null or undefined.");
256 | this._present(word, "The word provided to Speech#phoneme(..) was null or undefined.");
257 | var escapedWord = this._escape(word);
258 | if (ph.indexOf("'") !== -1) {
259 | ph = ph.replace(/'/g, ''')
260 | }
261 | this._elements.push("" + escapedWord + "");
262 | return this;
263 | };
264 |
265 | /**
266 | * This method escapes any special characters that will cause SSML to be invalid.
267 | * @param word being the text to insert
268 | * @returns {*}
269 | * @private
270 | */
271 | Speech.prototype._escape = function (word) {
272 | if (typeof(word) === "string") {
273 | word = word.replace(/&/g, '&');
274 | word = word.replace(//g, '>');
276 | word = word.replace(/"/g, '"');
277 | word = word.replace(/'/g, ''');
278 | return word;
279 | }
280 | if (typeof(word) === "number") {
281 | return word;
282 | }
283 | if (typeof(word) === "boolean") {
284 | return word;
285 | }
286 | throw new Error('received invalid type ' + typeof(word));
287 | };
288 |
289 | /**
290 | * This method ensures the input passing in is not null, undefined or empty string. In the case that it is, an exception is thrown with the message provided.
291 | * @param word
292 | * @param msg
293 | * @private
294 | */
295 | Speech.prototype._notEmpty = function (word, msg) {
296 | this._present(word, msg);
297 | if (word.length === 0) {
298 | throw msg;
299 | }
300 | };
301 |
302 | /**
303 | * Ensures 'fnc' is a function.
304 | * @param fnc the variable to check if it's a function.
305 | * @param name the name of the parameter used in the error message.
306 | */
307 | Speech.prototype._isFunction = function (fnc, name) {
308 | var fncType = typeof(fnc);
309 | if (fncType !== "function") {
310 | throw new Error(name + " was not a function. received: " + fncType);
311 | }
312 | };
313 |
314 | /**
315 | * Creates and inserts a emphasis tag.
316 | * see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference#emphasis
317 | * @param level includes strong, moderate and reduced
318 | * @param word word or text to insert
319 | * @returns {Speech}
320 | */
321 | Speech.prototype.emphasis = function (level, word) {
322 | this._present(level, "The level provided to Speech#emphasis(..) was null or undefined");
323 | this._present(word, "The word provided to Speech#emphasis(..) was null or undefined");
324 | var levels = ['strong', 'moderate', 'reduced'];
325 | if (levels.indexOf(level) < 0) {
326 | throw new Error("The level provided to Speech#emphasis(..) was not valid. Received level: " + level);
327 | }
328 |
329 | this._notEmpty(word, "The word provided to Speech#emphasis(..) was empty");
330 | this._elements.push("" + this._escape(word) + "");
331 | return this;
332 | };
333 |
334 | /**
335 | * √ TODO: Handle rate minimum 20%
336 | * @param attributes
337 | * @param word
338 | * @returns {Speech}
339 | */
340 | Speech.prototype.prosody = function (attributes, word) {
341 | this._present(attributes, "The attributes provided to Speech#prosody(..) was null or undefined");
342 | this._present(word, "The word provided to Speech#prosody(..) was null or undefined");
343 | this._notEmpty(word, "The word provided to Speech#prosody(..) was empty");
344 |
345 | var validRates = ['x-slow', 'slow', 'medium', 'fast', 'x-fast'];
346 | var validPitches = ['x-low', 'low', 'medium', 'high', 'x-high'];
347 | var validVolumes = ['silent', 'x-soft', 'soft', 'medium', 'loud', 'x-loud'];
348 |
349 | var final = "" + this._escape(word) + "";
381 | this._elements.push(final);
382 | return this;
383 |
384 | };
385 |
386 | /**
387 | * This helper function consolidates the validation checks for rate,pitch and volume. It will first
388 | * check to see if the attribute is present and whether it's one of the following conditions:
389 | * a) the value of the attribute is a valid value or
390 | * b) the value does not exist in the list, but passes the onCheck function. A hook for additional checks.
391 | *
392 | * Upon passing the above checks, the onSuccessful function is called allowing the caller to do any additional work.
393 | *
394 | * @param obj The object that owns the attribute.
395 | * @param attribute The attribute name to check. e.g., rate, pitch or volume.
396 | * @param validList The list of value values that the attribute can be.
397 | * @param onCheck A hook for additional checks if the value does not exist in the list.
398 | * @param onSuccessful A hook to call when all validation checks succeed.
399 | */
400 | function validateAttribute(obj, attribute, validList, onCheck, onSuccessful) {
401 | if (obj.hasOwnProperty(attribute)) {
402 | obj[attribute] = obj[attribute].toLowerCase().trim();
403 | if (validList.indexOf(obj[attribute]) == -1) {
404 | onCheck();
405 | }
406 | onSuccessful();
407 | }
408 | }
409 |
410 | /**
411 | * This method ensures that the value of the rate must be equal or great than 20%
412 | * @param num is the value of rate
413 | */
414 | function checkRateRange(num) {
415 | var numString = num.substring(0, num.length - 1);
416 | var parseNum = parseInt(numString);
417 | if (parseNum < 20) {
418 | throw new Error("The minimum rate is twenty percentage. Received: " + parseNum);
419 | }
420 | }
421 |
422 | /**
423 | * This method lets the user provide an alias and pronounce the specified word or pharse as a different word or phrase
424 | * @param alias is the word that you want to pronounce instead of the original word
425 | * @param word
426 | * @returns {Speech}
427 | */
428 | Speech.prototype.sub = function (alias, word) {
429 | this._present(alias, "The alias provided to Speech#sub(..) was null or undefined");
430 | this._notEmpty(alias, "The alias provided to Speech#sub(..) was empty");
431 | this._present(word, "The word provided to Speech#sub(..) was null or undefined");
432 | this._notEmpty(word, "The word provided to Speech#sub(..) was empty");
433 |
434 | this._elements.push("" + this._escape(word) + "");
435 | return this;
436 | };
437 |
438 | /**
439 | * This method lets the user add raw SSML into the speech object without escaping the special characters.
440 | * For example, if you passed in "Hi", it won't escape the less than or greater than tags.
441 | * @param saying raw string to be appended
442 | * @returns {Speech}
443 | */
444 | Speech.prototype.sayWithSSML = function (saying) {
445 | this._present(saying, "The saying provided to Speech#sayWithSSML(..) was null or undefined.");
446 | this._elements.push(saying);
447 | return this;
448 | };
449 |
450 | /**
451 | * This method will select a random word or phrase from the choices provided and then say it to the user
452 | * @param choices - an array of phrases or words
453 | * @returns {Speech}
454 | */
455 | Speech.prototype.sayRandomChoice = function (choices) {
456 | var choice = this._helper.chooseRandomWord(choices);
457 | this._elements.push(this._escape(choice));
458 | return this;
459 | };
460 |
461 | /**
462 | * This method validates if the value exists in the list of values
463 | * @param value
464 | * @param listOfValues
465 | * @param msg is the error message that will be thrown when the value is not in the list
466 | */
467 | function isInList(value, listOfValues, msg) {
468 | value = value.toLowerCase().trim();
469 | if (listOfValues.indexOf(value) === -1) {
470 | throw new Error(msg);
471 | }
472 | }
473 |
474 | module.exports = Speech;
475 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ssml-builder",
3 | "version": "0.4.3",
4 | "description": "This package creates Speech Synthesis Markup Language (SSML) using the builder pattern.",
5 | "main": "index.js",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "scripts": {
10 | "test": "./node_modules/mocha/bin/mocha test"
11 | },
12 | "keywords": [
13 | "ssml",
14 | "amazon",
15 | "alexa",
16 | "google",
17 | "actions",
18 | "actions-on-google",
19 | "google-assistant",
20 | "voice",
21 | "alexa-skill",
22 | "node",
23 | "skill"
24 | ],
25 | "repository": {
26 | "type": "git",
27 | "url": "https://github.com/mandnyc/ssml-builder"
28 | },
29 | "author": "Mandy Chan",
30 | "license": "Apache-2.0",
31 | "devDependencies": {
32 | "chai": "^3.5.0",
33 | "mocha": "^2.5.3"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/test/amazon_speech_test.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var assert = require('chai').assert;
4 | var AmazonSpeech = require("../amazon_speech.js");
5 |
6 | describe('AmazonSpeech', function () {
7 |
8 | describe('wispher', function () {
9 |
10 | var amazon_speech = null;
11 |
12 | describe('positive', function () {
13 |
14 | beforeEach(function () {
15 | amazon_speech = new AmazonSpeech();
16 | });
17 |
18 | it('should create the tag', function () {
19 | amazon_speech.whisper("good night and sweet dreams");
20 | assert.equal(amazon_speech.ssml(), "good night and sweet dreams")
21 | });
22 |
23 | it('should create the tag with special characters', function () {
24 | amazon_speech.whisper("good night & sweet dreams");
25 | assert.equal(amazon_speech.ssml(), "good night & sweet dreams")
26 | });
27 | });
28 |
29 | describe('negative', function () {
30 |
31 | beforeEach(function () {
32 | amazon_speech = new AmazonSpeech();
33 | });
34 |
35 | it('should expect a missing argument for whisper ', function () {
36 | assert.throws(function () {
37 | amazon_speech.whisper();
38 | }, "The words provided to AmazonSpeech#whisper(..) was 'undefined'");
39 | });
40 |
41 | it('should throw an exception because of a null input for whisper ', function () {
42 | assert.throws(function () {
43 | amazon_speech.whisper(null);
44 | }, "The words provided to AmazonSpeech#whisper(..) was 'null'");
45 | });
46 |
47 | it('should throw an exception because of an empty string input for whisper ', function () {
48 | assert.throws(function () {
49 | amazon_speech.whisper("");
50 | }, "The words provided to AmazonSpeech#whisper(..) was ''");
51 | });
52 | })
53 | });
54 |
55 | });
56 |
57 |
58 | // var speech = new AmazonSpeech();
59 | // speech.whisper("good night and sweet dreams").pause("1ms");
60 | // console.log(speech.ssml());
61 |
--------------------------------------------------------------------------------
/test/speech_test.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var assert = require('chai').assert;
4 | var Speech = require('../index');
5 |
6 | describe('Speech', function () {
7 |
8 | var speech = null;
9 |
10 | describe('basics', function () {
11 |
12 | beforeEach(function () {
13 | speech = new Speech();
14 | });
15 |
16 | describe('say', function () {
17 |
18 | it('should generate a saying tag2', function () {
19 | speech.say("star");
20 | assert.equal(speech.ssml(), "star");
21 | });
22 |
23 | it('say should escape characters', function () {
24 | speech.say("");
25 | assert.equal(speech.ssml(), "<star's>");
26 | });
27 |
28 | it('say should escape characters', function () {
29 | speech.say('');
30 | assert.equal(speech.ssml(), "<star"s>");
31 | });
32 |
33 | it('should generate a saying tag', function () {
34 | speech.say("hi");
35 | assert.equal(speech.ssml(), "hi");
36 | });
37 |
38 | });
39 |
40 | describe('paragraph', function () {
41 |
42 | it('should build a paragraph tag', function () {
43 | speech.paragraph("hi");
44 | assert.equal(speech.ssml(), "