applied cognitive computing fall 2016 android application ...€¦ · applied cognitive computing...

11
Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise, we will create a simple Android application that uses IBM Bluemix’ text-to-speech web service. The application will have one activity where two UI components will be shown: and input textbox and a button. The purpose of the app is to read the text in the textbox and use it as input to IBM’s text-to-speech web service. The web service will return an audio file, which the app will play as soon as it is received. 1. Open Android Studio, click on File->New ->New Project (you are free to use any application name and company domain)

Upload: others

Post on 30-Apr-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

AppliedCognitiveComputingFall2016

AndroidApplication+IBMBluemix(Text-to-speech)

Inthisfirstexercise,wewillcreateasimpleAndroidapplicationthatusesIBMBluemix’text-to-speechwebservice.TheapplicationwillhaveoneactivitywheretwoUIcomponentswillbeshown:andinputtextboxandabutton.ThepurposeoftheappistoreadthetextinthetextboxanduseitasinputtoIBM’stext-to-speechwebservice.Thewebservicewillreturnanaudiofile,whichtheappwillplayassoonasitisreceived.

1. OpenAndroidStudio,clickonFile->New->NewProject(youarefreetouseanyapplicationnameandcompanydomain)

Page 2: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

2. ClickonNext,andmakesureonly“PhoneanTablet”ischecked.MakesureminimumSDKissettoAPI19orgreater.

3. ClickonNext,andselectEmptyActivity.

4. ClickonNext,andthenclickonFinish

Page 3: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

5. Openapp->java->res->layout->activity_main.xml.Then,clickonText

Page 4: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

6. ModifytheXMLfile,sothatitlookslikethis:<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="DO NOT CHANGE ANYTHING HERE - Diego"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Make Web Service Call" android:id="@+id/button" android:layout_below="@+id/editText" android:layout_centerHorizontal="true" /> </RelativeLayout>

7. Openapp->java->---context----->MainActivity.java

8. Addthefollowingmethod:

Page 5: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

private void addButtonListener() { Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "Hi! Testing button...", Toast.LENGTH_SHORT).show(); } }); }

9. CalladdButtonListener()rightaftersetContentView(R.layout.activity_main);

10. Runyourapplication,andtapthe“Makewebservicecall”button.Amessageshouldbedisplayed.

11. AddthefollowingmethodtoyourMainActivityClass

private String getTextFromEditText() { EditText editText = (EditText) findViewById(R.id.editText); return editText.getText().toString(); }

12. ModifytheaddButtonListener()method,sothatitlookslikethis:private void addButtonListener() { Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String inputText = getTextFromEditText(); Toast.makeText(getApplicationContext(), "Hi! Your input: " + inputText, Toast.LENGTH_SHORT).show(); } }); }

13. Runyourapplication,addsometexttothetextbox,andtapthe“Makewebservicecall”button.Whateveryoutypedshouldbedisplayedonthescreen.

14. Ifeverythingisworkingasexpected,wearereadytocommunicatewithBluemix.Gotothispage:https://new-console.ng.bluemix.net/andlogin

15. ClickonCatalog

Page 6: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

16. SelectWatson,andthenclickon“Texttospeech”

17. ScrolltothebottomofthepageandclickonCreate

Page 7: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

18. ClickonServiceCredentialsandthenclickonViewCredentials

19. You’llseetheURLyouwillbeusingtocommunicatewiththeservicealongwithyourusernameandpassword.Don’tclosethiswindow/tab,wewilluselateron.

20. GobacktoyourAndroidProjectandopenGradleScripts->build.gradle(Module:app).Addthefollowingtwolinesinthedependenciessection:

compile 'com.google.code.gson:gson:2.2.4' compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2' compile 'com.ibm.watson.developer_cloud:java-sdk:3.3.0'

21. Openapp->manifests->AndroidManifest.xmlandaddthefollowinglines<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Page 8: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

22. CreateanewJavaclassandnameitTextToSpeechWebServiceHandler.This

newfileshouldcontainthefollowing:package YOUR PACKAGE NAME!! import android.content.Context; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.AudioFormat; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; public class TextToSpeechWebServiceHandler { private final String WEBSERVICE_URL = "https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize"; private final String USERNAME = "your username goes here"; private final String PASSWORD = "your password goes here";

Page 9: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

private String type = "POST"; private Context appContext; private File convertedFile; private String inputText; public TextToSpeechWebServiceHandler(Context appContext) { this.appContext = appContext; } public void execute(String inputText) { this.inputText = inputText; new TheTask().execute(WEBSERVICE_URL); } class TheTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... arg0) { String text = null; try { com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech service = new com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech(); service.setUsernameAndPassword(USERNAME, PASSWORD); try { text = inputText; InputStream stream = service.synthesize(text, Voice.EN_ALLISON, AudioFormat.OGG_VORBIS).execute(); File downloadsFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); convertedFile = new File(downloadsFolder, "test.ogg");//File.createTempFile("convertedFile", ".ogg", downloadsFolder); FileOutputStream out = new FileOutputStream(convertedFile); byte[] buffer = new byte[1024]; int length; while ((length = stream.read(buffer)) > 0) { out.write(buffer, 0, length); } out.close(); stream.close(); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } return text; } public void playFile() { try {

Page 10: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

FileInputStream fis = new FileInputStream(convertedFile); MediaPlayer mp = new MediaPlayer(); mp.setDataSource(fis.getFD()); mp.prepare(); mp.start(); } catch (Exception e) { Log.e("MEDIA", e.toString()); e.printStackTrace(); } }//end playFile @Override protected void onPostExecute(String result) { super.onPostExecute(result); playFile(); } } }

23. LocatetheconstantsUSERNAMEandPASSWORDandupdatethem(useyourusernameandpasswordfromstep18)

24. GobacktoMainActivity.javaandaddthefollowingtwolines:TextToSpeechWebServiceHandler ttswsh = new TextToSpeechWebServiceHandler(getApplicationContext()); ttswsh.execute(inputText);

Page 11: Applied Cognitive Computing Fall 2016 Android Application ...€¦ · Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Text-to-speech) In this first exercise,

25. Runyourapplicationandtestit!