Archive for the ‘code’ Category.

Text to speech sample in C#

I found out that I had not played with Text to speech in .net yet. So naturally I went to take a look how easy or hard it is to use TTS in C#. It turns out the hardest part is to find the download link for the TTS install. Its hard to understand how Microsoft sometimes seems to hide download links. Once you find the SAPI SDK page, you would think they would have download links, but not so. However you do not need the whole SDK just to do Text to speech. You only need the TTS download which has a much smaller footprint. But again, where is the download link… ? I found one Microsoft page that doesn’t make it clear, and another third party page that I used to download the TTS install.

And now for the code it self, it’s very straight forward. After installing TTS add reference to your project, choose the COM “Microsoft Speech Object Library” that will create interop dll for your project. Add a reference to the speech library in code and the Hello world sample is only two lines of code.

using System;
//
using SpeechLib;

namespace tester
{
    class Program
    {
        static void Main(string[] args)
        {
            SpVoice myVoice = new SpVoice();
            myVoice.Speak(“Hello world”);
        }
    }
}

Another choice is to do the same without using the COM object, as COM is heavy. In that case add reference to System.Speech .net library and the code will look like this.

using System;
//
using System.Speech.Synthesis;

namespace tester
{
    class Program
    {
        static void Main(string[] args)
        {
            SpeechSynthesizer synth = new SpeechSynthesizer();
            synth.Speak(“Hello World”);
        }
    }
}

TeamCity Twitter plugin, part 2

I had to fix an old plugin I made some time back, I did actually post about it here Java Authenticated POST. So why bring it up again, a good question I say. As Twitter changed their authentication sometime late last year ( Nov 2010 ? ). All programs using the old authentication stopped working. I hadn’t had / given myself time to look at the broken plugin. What the TeamCity twitter plugin does it to tweet when the TeamCity server starts and ends builds. If you follow that account you get notified on Twitter without having to open up your email box to see how your builds are doing.
I went googling about the new authentication and found a nice snippet on StackOverflow The snippet uses Twitter4J library to make the task really simple, check them out. The best part is that Twitter4J only needs Java 1.4 to run. That’s great as my TeamCity server only has Java 1.5 and not the newer 1.6, further as an added bonus their core jar is only 280k, that’s all I needed. Below is my code modified from the StackOverflow sample. It works fine if you are only posting to one account. The tokens and keys can be found on your Twitter app page. If you need to post for different users from your application then your code needs to take that into account. If you want the source of the plugin or all 3 plugins I have created, you can run over to GitHub and pick it up. I made it public domain, open source, whatever you want to call it.

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.*;;

   // Updates the twitter account
   public static void sendTweet( String psText )
   {
           try
           {
                        // Configuration
                        ConfigurationBuilder confbuilder = new ConfigurationBuilder();
                        confbuilder.setOAuthAccessToken(CxGlobal.ACCESS_TOKEN_KEY)
                        .setOAuthAccessTokenSecret(CxGlobal.ACCESS_TOKEN_SECRET)
                        .setOAuthConsumerKey(CxGlobal.CONSUMER_KEY)
                        .setOAuthConsumerSecret(CxGlobal.CONSUMER_SECRET);
                                               
                        // get the interaction object
                        Twitter twitter = new TwitterFactory(confbuilder.build()).getInstance();
                        // send
                        twitter4j.Status status = twitter.updateStatus( psText );
                        //
                        //System.out.println("*** Response=" + status.getText() );
           }
           catch( Exception ex )
           {
               System.out.println( “***ERROR=” + stack2string( ex ));
               LOG.info( “***ERROR=” + stack2string( ex ) );
           }
   }

Edit, the 3 plugins have now been added to the official TeamCity PlugIn page

Non compliant XML in Configuration file Base64

I had a need to store some configuration data that is non XML compliant in my .net configuration file. As the configuration file is XML file I settled on storing the data in Base64 and then converting it back after it’s read from the configuration file. First we take the string and convert it to bytes then we convert the bytes to Base64 string that will be written to the configuration file. Reverse when you want to read the string from the configuration file.

And now for the code, as a UnitTest

// C#
string original = “&at;=@|”=’_EMPTY_'”;
// base64 value = JmF0Oz1AfCcnPSdfRU1QVFlfJw==

// to bytes and back test
byte[] dBytes = new System.Text.UTF8Encoding().GetBytes( original );
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string str = enc.GetString(dBytes);
// compare
Assert.AreEqual( original, str);

// This is the string to put in the configuration file now Base64 formatted
string base64String = Convert.ToBase64String( dBytes );
// config string base64 value=JmF0Oz1AfCcnPSdfRU1QVFlfJw==
Console.WriteLine( “config string base64 value=”+ base64String );

// Convert Base64 back to a normal string, this needs to be done after reading
// the base 64 string from the config file
byte[] nonBase64bytes = Convert.FromBase64String( base64String );
// string from bytes
string fromBytes = new System.Text.UTF8Encoding().GetString(nonBase64bytes);
// Make sure it still adds up with the original
Assert.AreEqual(original, fromBytes );

Android play instant sound from resource

I wanted to play short sound bites in a Android application, when playing sounds on the Media player there is a lag as the Media player needs to allocate memory, load the resource etc. If you need to play short sounds in response to button click or when shooting a gun in your game you need it to play instantly in response to what the user just did. In that respect SoundPool is the way to go, it allows preloading the soundbites and gives instant access to the sounds as needed. I created a simple convenience class for it as seen below.

//
package us.kristjansson.android.util;
//
import android.media.AudioManager;
import android.media.SoundPool;
import android.app.Activity;
//
import java.util.HashMap;
//
import us.kristjansson.android.R;

public class CxMediaPlayer
{
private SoundPool mShortPlayer= null;
private HashMap mSounds = new HashMap();

// Constructor
public CxMediaPlayer( Activity pContext )
{
// setup Soundpool
this.mShortPlayer = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);

// 0-9 Buttons
mSounds.put( R.raw.button_1, this.mShortPlayer.load(pContext, R.raw.button_1, 1) );
mSounds.put( R.raw.button_2, this.mShortPlayer.load(pContext, R.raw.button_2, 1) );
mSounds.put( R.raw.button_3, this.mShortPlayer.load(pContext, R.raw.button_3, 1) );
mSounds.put( R.raw.button_4, this.mShortPlayer.load(pContext, R.raw.button_4, 1) );
mSounds.put( R.raw.button_5, this.mShortPlayer.load(pContext, R.raw.button_5, 1) );
mSounds.put( R.raw.button_6, this.mShortPlayer.load(pContext, R.raw.button_6, 1) );
mSounds.put( R.raw.button_7, this.mShortPlayer.load(pContext, R.raw.button_7, 1) );

// Others
mSounds.put( R.raw.delete_5, this.mShortPlayer.load(pContext, R.raw.correct_answer, 1) );
mSounds.put( R.raw.delete_5, this.mShortPlayer.load(pContext, R.raw.wrong_answer, 1) );
}

// Plays the passed preloaded resource
public void playShortResource( int piResource )
{
int iSoundId = mSounds.get( piResource );
this.mShortPlayer.play( iSoundId, 0.99f, 0.99f, 0, 0, 1 );
}

// Cleanup
public void Release()
{
// Cleanup
this.mShortPlayer.release();
this.mShortPlayer = null;
}
}

Then all you need in your Activity is to initiate the player class and call playShortResource when you need a sound played. Your resources should be available in the res/raw directory.

// The media player – OnCreate
  mxMediaPlayer = new CxMediaPlayer( this );
// Play the desired sound – OnClick
  mxMediaPlayer.playShortResource(  R.raw.button_1 );
// Make sure to release resources when done – OnDestroy
  mxMediaPlayer.Release();

Android GUI thread timer sample

I was looking for a simple Android timer to do updates on ticks in one of the views I’m playing with. The problem with spinning off another thread brings up two issues, one is that it takes more resources and the second one is that you will have to switch back over to the UI thread to update the screen. Then I came across a much better solution in the SDK documentation click here. I had to read it a couple of times and when I imported it into my app had to figure out some things a long the way. So for your benefit here is a cut down simple version.

In case you didn’t know see how easy it’s to use the built in Log class, the output will be visible in LogCat output. Also note the call Handler.removeCallbacks(mUpdateTimeTask); to free resources.

//
package us.kristjansson.test;
//
import us.kristjansson.test.R;
//
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
//

public class FxFireWorks extends Activity
{
        // Timer
        private Handler mHandler = new Handler();
        //
        private Runnable mUpdateTimeTask = new Runnable()
        {
           public void run()
           {
               // Do something
               Log.d( this.toString(), “Do something !!”);
               // timer
               mHandler.postDelayed(mUpdateTimeTask, ( 2 * 1000)) ;
           }
        };
       
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // Hide the title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fireworks);
   
        // timer
        mHandler.removeCallbacks(mUpdateTimeTask);
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    @Override
    public void onStop()
    {
        super.onStop();
       
        // timer
        mHandler.removeCallbacks(mUpdateTimeTask);
    }
   
}

Adobe Air development

I was talking to a friend about lack of a good interface for discovering NetFlix movies that do actually stream. The problem is that most of the movies are DVD distribution only. Further the streaming movies are sometimes streaming and sometimes not. It has something to do about when they are showing on TV. If your like me, you want to watch your movie at the end of the day when there is nothing on TV. In that case you want it streaming right there and then.

So I figure why not create a small app that will keep a list of the movies your wanting to see and it should be able to refresh and show you which ones are available for NetFlix streaming at any given time. Sounds easy enough, but there is a catch, I wanted it cross platform as my friend mostly uses a Mac. Hmm so I was thinking that’s easy enough just create simple C# program that will run smoothly on Mac under Mono. No that’s too easy, then it came to me, I have wanted to look at Adobe Air apps, this is a perfect opportunity. Let’s give it a try, as added bonus I wanted to do some dev on my Linux box. It should be fun to create this little app on the Linux and have it run on PC and Mac as well.

Well it turns out that Adobe only supports the FlashBuilder on Win and Mac, no Linux for you my friend. But we don’t give up that easily, I don’t want to run under Wine, turn to google and I find Fb4Linux. As it turns out after installing a bunch of libs and the FlashBuilder and some Sdks and such that I couldn’t get it to run under Linux ( I might try again later ). I’m probably not running the same versions of stuff as the author of the instructions, or maybe I just can’t follow instructions that well. Oh well, back to Windows, get the install from Adobe and it installs fine, then run the IDE, it plugs into Eclipse. Sure enough nothing to be found there, but wait a minute, not only do they ( claim to ) install it as plugin in your existing Eclipse, they also install a whole new instance of Eclipse. Sure enough when I run that new instance FB comes up and works as expected, you can start a new FB project etc.

Now with all the install trouble out of the way let’s give it a spin. File -> New Flex Project, the basics are setup for you by the wizard. Drag a couple of controls on the panel, goto properties and create click event for the button, there you have it “Hello World” Then click export, go through the wizard and an .air install file has been created. That’s pretty nice considering that I didn’t read any quick starts tutorials. But wait a minute, I click the air file to run it on my desktop and get some error indicating corrupted Air install file, contact the provider for a new file etc. Google search to the rescue and after un-installing and re-installing Air, nothing had changed. Then I uncheck the option of having a Timestamp in the digital signature of the .air file and that did the trick, now I can run and install, uhh.

Things seem to be looking up, time to code this puppy….. when I get to it, not sure if I’m going to pursue that or not, might be a follow up post. Notice all the javascript, might be too web-ish for my taste.

Here is Hello World in code

<?xml version=“1.0” encoding=“utf-8”?>
<s:WindowedApplication xmlns:fx=“http://ns.adobe.com/mxml/2009”
                                           xmlns:s=“library://ns.adobe.com/flex/spark”
                                           xmlns:mx=“library://ns.adobe.com/flex/mx”>

                <fx:Script>
                <![CDATA[
                        import mx.events.FlexEvent;
                       
                        protected function button1_clickHandler(event:MouseEvent):void
                        {
                                txSome.text = “Hello World !”;
                        }
                ]]>
        </fx:Script>

        <fx:Declarations>
                <!– Place non-visual elements (e.g., services, value objects) here –>
        </fx:Declarations>
        <s:Button x=“37” y=“10” label=“Button” click=“button1_clickHandler(event)”/>
        <s:TextArea x=“37” y=“52” id=“txSome”/>
</s:WindowedApplication>

And the app itself

Update
—–
I got Flex builder working later on the Linux box after some tinkering, that’s how the sample looks there.