2013年4月23日 星期二

jarvis 000


package com.example.texttospeech;

import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import android.util.Log;

public class MainActivity extends Activity implements
TextToSpeech.OnInitListener {
private static final String TAG = "TextToSpeechDemo";

private TextToSpeech mTts;
String resultstr;

private TextView mText;
private SpeechRecognizer sr;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// 初始化TextToSpeech对象. 是一个异步操作.
// 初始化监听对象,在完成初始化时调用
mTts = new TextToSpeech(this, this);
listen_speak();


}

@Override
public void onDestroy() {
if (mTts != null) {
// 停止TextToSpeech
mTts.stop();
// 释放TextToSpeech占用的资源
mTts.shutdown();
}
super.onDestroy();
}

// 实现TextToSpeech.OnInitListener接口.
public void onInit(int status) {
// 状态成功
if (status == TextToSpeech.SUCCESS) {
// 设置语言
int result = mTts.setLanguage(Locale.ENGLISH);
// (我试了中文,不好使????)
// int result = mTts.setLanguage(Locale.CHINA);

if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
// 如果不支持该语言
Toast.makeText(getApplicationContext(), "not support this lan",
Toast.LENGTH_SHORT).show();
} else {
// TTS 引擎已经成功初始化
// 按钮设置为可点击
//Button "button1"
Button button1 = (Button) findViewById(R.id.button1);
       button1.setOnClickListener(new Button.OnClickListener()
       {
         public void onClick(View v)
         {
         //To-Do
         listen_speak();
         }
       });
//End of Button "button1"
// 发音朗读
// say("Hello");

}
} else {
// 初始化失败
Toast.makeText(getApplicationContext(), "first fail",
Toast.LENGTH_SHORT).show();
}
}

private void say(String hello) {
// Select a random hello.

// 朗读
mTts.speak(hello, TextToSpeech.QUEUE_FLUSH, null);


}

private void speak() {
// TODO Auto-generated method stub
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
"voice.recognition.test");

intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
sr.startListening(intent);
Log.i("111111", "11111111");

}

class listener implements RecognitionListener {
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "onReadyForSpeech");
}

public void onBeginningOfSpeech() {
Log.d(TAG, "onBeginningOfSpeech");
}

public void onRmsChanged(float rmsdB) {
Log.d(TAG, "onRmsChanged");
}

public void onBufferReceived(byte[] buffer) {
Log.d(TAG, "onBufferReceived");
}

public void onEndOfSpeech() {
Log.d(TAG, "onEndofSpeech");
}

public void onError(int error) {
Log.d(TAG, "error " + error);
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}

public void onResults(Bundle results) {
String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList data = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++) {
Log.d(TAG, "result " + data.get(i));
str += (data.get(i) + ", ");
}
Toast.makeText(getApplicationContext(), "You said: " + data.get(0),
Toast.LENGTH_SHORT).show();
if (data.get(0).equals("hello") || data.get(0).equals("hi"))
say("Ok hi");
else if(data.get(0).equals("fuck you"))
say("don't fuck me");
else if(data.get(0).equals("who are you"))
say("i'm jarvis");
else if(data.get(0).equals("wing man")||data.get(0).equals("wingman"))
say("she is beautiful");
else if(data.get(0).equals("我好悶呀")){
String videoId = "H542nLTTbu0";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId));
intent.putExtra("VIDEO_ID", videoId);
startActivity(intent);
say("watch some video");
}

else
say("i don't know what are you talking about");

}

public void onPartialResults(Bundle partialResults) {
Log.d(TAG, "onPartialResults");
}

public void onEvent(int eventType, Bundle params) {
Log.d(TAG, "onEvent " + eventType);
}
}

public void listen_speak() {
// TODO Auto-generated method stub

sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());

speak();
}
}

2013年4月16日 星期二

Progress bar and downloading a file sample program in Android


Progress bar and downloading a file sample program in Android

By: Ashley Emailed: 225 times Printed: 369 times   
   
Latest comments
By: vikas jain - Which one is the inbuilt
By: JC - In listing 6.2 I don't se
By: md arif alam - i have to learn java
By: jimoh abiodun - why can't we download & i
By: Rekha - please send me basic prog
By: Zs - Thank you, saved my life
By: Chinzoo - How to delete file button
By: bmnaidu - i have completed B.Tech,i
By: vikas - its not sufficient add mo
This sample android program shows you how to show Progress Bar in Android. In this program many concepts are explained. A button is shown and when clicked, a big file is downloaded from flickr. The downloaded file is saved to the sdcard in the android phone. While the download is still in progress, a progress bar is shown with the actual percentage of download. So the code below explains, downloading a file from a server, saving a file to the sdcard and showing a progress bar all in one android program.
The download.java file is as follows:
package com.javasamples;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class download extends Activity {
   
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        new DownloadFileAsync().execute(url);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
  case DIALOG_DOWNLOAD_PROGRESS:
   mProgressDialog = new ProgressDialog(this);
   mProgressDialog.setMessage("Downloading file..");
   mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
   mProgressDialog.setCancelable(false);
   mProgressDialog.show();
   return mProgressDialog;
  default:
   return null;
        }
    }

class DownloadFileAsync extends AsyncTask<String, String, String> {
   
 @Override
 protected void onPreExecute() {
  super.onPreExecute();
  showDialog(DIALOG_DOWNLOAD_PROGRESS);
 }

 @Override
 protected String doInBackground(String... aurl) {
  int count;

 try {

 URL url = new URL(aurl[0]);
 URLConnection conexion = url.openConnection();
 conexion.connect();

 int lenghtOfFile = conexion.getContentLength();
 Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

 InputStream input = new BufferedInputStream(url.openStream());
 OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

 byte data[] = new byte[1024];

 long total = 0;

  while ((count = input.read(data)) != -1) {
   total += count;
   publishProgress(""+(int)((total*100)/lenghtOfFile));
   output.write(data, 0, count);
  }

  output.flush();
  output.close();
  input.close();
 } catch (Exception e) {}
 return null;

 }
 protected void onProgressUpdate(String... progress) {
   Log.d("ANDRO_ASYNC",progress[0]);
   mProgressDialog.setProgress(Integer.parseInt(progress[0]));
 }

 @Override
 protected void onPostExecute(String unused) {
  dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
 }
}
}
The output of this program will be as shown in the android emulator below.
The main.xml file in your res/layout folder is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello" />
 <Button
  android:text="Start long running task.."
  android:id="@+id/startBtn"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
 </Button>
</LinearLayout>

2013年4月14日 星期日

Android(朗读文本) TextToSpeech的使用


使用TextToSpeech 可以朗读文本,要先初始化TextToSpeech 对象,通过实现TextToSpeech.OnInitListener接口来检测初始化状态成功与否(设置语言等动作是否成功),初始化成功后,才可以使用,用完该对象后,要调用shutdown方法,释放TextToSpeech (TTS)引擎占用的资源
Java代码  收藏代码
  1. package com.zhou.activity;  
  2.   
  3. import java.util.Locale;  
  4. import java.util.Random;  
  5.   
  6. import android.app.Activity;  
  7. import android.os.Bundle;  
  8. import android.speech.tts.TextToSpeech;  
  9. import android.util.Log;  
  10. import android.view.View;  
  11. import android.widget.Button;  
  12.   
  13. public class TextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener{  
  14.       private static final String TAG = "TextToSpeechDemo";  
  15.   
  16.         private TextToSpeech mTts;  
  17.         private Button mAgainButton;  
  18.   
  19.         @Override  
  20.         public void onCreate(Bundle savedInstanceState) {  
  21.             super.onCreate(savedInstanceState);  
  22.             setContentView(R.layout.text_to_speech);  
  23.   
  24.             // 初始化TextToSpeech对象. 是一个异步操作.  
  25.             // 初始化监听对象,在完成初始化时调用  
  26.             mTts = new TextToSpeech(this,this);  
  27.             //取得按钮  
  28.             mAgainButton = (Button) findViewById(R.id.again_button);  
  29.             //为按钮设置单击事件  
  30.             mAgainButton.setOnClickListener(new View.OnClickListener() {  
  31.                 public void onClick(View v) {  
  32.                     sayHello();  
  33.                 }  
  34.             });  
  35.         }  
  36.   
  37.         @Override  
  38.         public void onDestroy() {  
  39.             if (mTts != null) {  
  40.                 //停止TextToSpeech  
  41.                 mTts.stop();  
  42.                 //释放TextToSpeech占用的资源  
  43.                 mTts.shutdown();  
  44.             }  
  45.             super.onDestroy();  
  46.         }  
  47.   
  48.         //实现TextToSpeech.OnInitListener接口.  
  49.         public void onInit(int status) {  
  50.             //状态成功  
  51.             if (status == TextToSpeech.SUCCESS) {  
  52.                //设置语言  
  53.                 int result = mTts.setLanguage(Locale.US);  
  54.                 //(我试了中文,不好使????)  
  55. //              int result = mTts.setLanguage(Locale.CHINA);  
  56.                 
  57.                 if (result == TextToSpeech.LANG_MISSING_DATA ||  
  58.                     result == TextToSpeech.LANG_NOT_SUPPORTED) {  
  59.                    // 如果不支持该语言  
  60.                     Log.e(TAG, "Language is not available.");  
  61.                 } else {  
  62.                     // TTS 引擎已经成功初始化   
  63.                     //按钮设置为可点击  
  64.                     mAgainButton.setEnabled(true);  
  65.                     //发音朗读  
  66.                     sayHello();  
  67.                 }  
  68.             } else {  
  69.                 // 初始化失败  
  70.                 Log.e(TAG, "Could not initialize TextToSpeech.");  
  71.             }  
  72.         }  
  73.   
  74.         private static final Random RANDOM = new Random();  
  75.         private static final String[] HELLOS = {  
  76.           "Hello",  
  77.           "Salutations",  
  78.           "Greetings",  
  79.           "Howdy",  
  80.           "What's crack-a-lackin?",  
  81.           "That explains the stench!"  
  82.         };  
  83.         //尝试朗读中文,失败了,语言设置为中国的也不行  
  84. //      private static final String[] HELLOS = {  
  85. //            "中国",  
  86. //            "北京",  
  87. //            "上海",  
  88. //            "吉林",  
  89. //            "辽宁",  
  90. //            "北京欢迎你"  
  91. //          };  
  92.         private void sayHello() {  
  93.             // Select a random hello.  
  94.             int helloLength = HELLOS.length;  
  95.             String hello = HELLOS[RANDOM.nextInt(helloLength)];  
  96.             //朗读  
  97.             mTts.speak(hello,TextToSpeech.QUEUE_FLUSH, null);  
  98.         }  
  99. }  

2013年4月10日 星期三

Set 音量 + Get 音量


AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 10, AudioManager.FLAG_SHOW_UI);

//音乐音量

int max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
int current = mAudioManager.getStreamVolume( AudioManager.STREAM_MUSIC );

change img of ImageView


ImageView img = new ImageView(this);  // or (ImageView) findViewById(R.id.myImageView);
img.setImageResource(R.drawable.my_image);

bg colour


RelativeLayout rl=(RelativeLayout)findViewById(R.id.your_layout_id);
rl.setBackgroundColor(Color.RED);
background colour bg

Hide Dialog 既 語音識別


package tif.makeyourjarvis;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import android.util.Log;



public class MainActivity extends Activity implements OnClickListener
{
String resultstr;

   private TextView mText;
   private SpeechRecognizer sr;
   private static final String TAG = "MyStt3Activity";
   @Override
   public void onCreate(Bundle savedInstanceState)
   {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //Button speakButton = (Button) findViewById(R.id.btn_speak);    
            //mText = (TextView) findViewById(R.id.textView1);    
            //speakButton.setOnClickListener(this);
            sr = SpeechRecognizer.createSpeechRecognizer(this);      
            sr.setRecognitionListener(new listener());    
           
            speak();
   }

   private void speak() {
// TODO Auto-generated method stub
  Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);      
       intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
       intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");

       intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
            sr.startListening(intent);
            Log.i("111111","11111111");

}

class listener implements RecognitionListener        
   {
            public void onReadyForSpeech(Bundle params)
            {
                     Log.d(TAG, "onReadyForSpeech");
            }
            public void onBeginningOfSpeech()
            {
                     Log.d(TAG, "onBeginningOfSpeech");
            }
            public void onRmsChanged(float rmsdB)
            {
                     Log.d(TAG, "onRmsChanged");
            }
            public void onBufferReceived(byte[] buffer)
            {
                     Log.d(TAG, "onBufferReceived");
            }
            public void onEndOfSpeech()
            {
                     Log.d(TAG, "onEndofSpeech");
            }
            public void onError(int error)
            {
                     Log.d(TAG,  "error " +  error);
                     Toast.makeText(getApplicationContext(), "error",Toast.LENGTH_SHORT).show();
            }
            public void onResults(Bundle results)                  
            {
                     String str = new String();
                     Log.d(TAG, "onResults " + results);
                     ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                     for (int i = 0; i < data.size(); i++)
                     {
                               Log.d(TAG, "result " + data.get(i));
                               str += (data.get(i)+", ");
                     }
                     Toast.makeText(getApplicationContext(), "results: "+str,Toast.LENGTH_SHORT).show();  
            }
            public void onPartialResults(Bundle partialResults)
            {
                     Log.d(TAG, "onPartialResults");
            }
            public void onEvent(int eventType, Bundle params)
            {
                     Log.d(TAG, "onEvent " + eventType);
            }
   }

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

}
}

語音識別


package tif.makeyourjarvis;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

//ListView mList = (ListView) findViewById(R.id.list);
 private static final int VOICE_RECOGNITION_REQUEST_CODE = 0;

@Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  startVoiceRecognitionActivity();
 
 }

 private void startVoiceRecognitionActivity()
 {
     //语音识别的Action
     Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
     //设置附加信息
     intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
     RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
     intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
     startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
 }

 protected void onActivityResult(int requestCode, int resultCode, Intent data)
 {
 if (requestCode==VOICE_RECOGNITION_REQUEST_CODE && resultCode==RESULT_OK)
      {

         ArrayList< String> matches=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
         //mList.setAdapter(new ArrayAdapter< String>(this,android.R.layout.simple_list_item_1,matches));
       
         Toast.makeText(getApplicationContext(),  matches.get(0),Toast.LENGTH_SHORT).show();
         startVoiceRecognitionActivity() ;
      }
 super.onActivityResult(requestCode, resultCode, data);
  }
}

Related Posts Plugin for WordPress, Blogger...