如何使用jcaptcha库实现声音验证码?

How to implement sound captcha using jcaptcha library?

我开始使用 jcaptcha library 为我的项目实现一个基于 captcha 的简单图像,并且进展顺利,运行良好。但现在我想将声音 captcha 功能与 image captcha 一起集成。请告诉我如何使用 Java.

中的 jcaptcha 库来实现它

这是我编写的代码片段:

//captcha engine config 

public class CustomCaptchaEngine extends ListImageCaptchaEngine {

@Override
protected void buildInitialFactories() {
    // TODO Auto-generated method stub

    WordGenerator wordGen=new RandomWordGenerator("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzxyz0123456789");

    RandomRangeColorGenerator colorGen=new RandomRangeColorGenerator(new int[]{100,255},new int[]{50,200}, new int[]{50,150});

    TextPaster textPaster = new RandomTextPaster(new Integer(4), new Integer(5), colorGen, Boolean.TRUE);

    BackgroundGenerator backgroundGenerator = new FileReaderRandomBackgroundGenerator(new Integer(200), new Integer(100), "C:/Users/pandabhi/eclipseworkspace/CaptchaTest/WebContent/captcha_backgrounds/");

    Font[] fontsList = new Font[] { new Font("Arial", Font.TYPE1_FONT, 10), new Font("Arial", 0, 14), new Font("Vardana", 0, 17), };

    FontGenerator fontGenerator = new RandomFontGenerator(20, 50, fontsList);

    WordToImage wordToImage=new ComposedWordToImage(fontGenerator, backgroundGenerator, textPaster);

    this.addFactory(new GimpyFactory(wordGen, wordToImage));
}

}


//captcha servlet 

public class ImageCaptchaServlet extends HttpServlet {


/**
 * 
 */
private static final long serialVersionUID = 1L;


public void init(ServletConfig servletConfig) throws ServletException {

    super.init(servletConfig);

}


protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {

   byte[] captchaChallengeAsJpeg = null;
   // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {
    // get the session id that will identify the generated captcha.
    //the same id must be used to validate the response, the session id is a good candidate!
    String captchaId = httpServletRequest.getSession().getId();
    // call the ImageCaptchaService getChallenge method
        BufferedImage challenge =
                CaptchaServiceInstance.getInstance().getImageChallengeForID(captchaId,
                        httpServletRequest.getLocale());

        // a jpeg encoder
        ImageIO.write(challenge, "jpg", jpegOutputStream);
    } catch (IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // flush it in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}
}

//captcha service instance 

public class CaptchaServiceInstance {

     private static ImageCaptchaService instance = 
                new DefaultManageableImageCaptchaService( new FastHashMapCaptchaStore(),new CustomCaptchaEngine(), 180,100000,75000);


public static ImageCaptchaService getInstance(){
    return instance;
}
}
// Captcha sound generator
//remember to change Voice.java file's deallocation() method as it was creating problems while compilation.Rebuild freetts source and use that.

public class CustomSoundCaptchaService {
private static SoundCaptchaService instanceSound=null;

public static SoundCaptchaService getInstance(WordGenerator wordGen){

     SoundConfigurator soundConfig = new FreeTTSSoundConfigurator("kevin16", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory", 1.0f, 100, 100);

     WordToSound word2sound = new FreeTTSWordToSound(soundConfig,6,7);

     CaptchaFactory[] factories = new CaptchaFactory[]{new GimpySoundFactory(wordGen, word2sound)};

     CaptchaEngine captchaEngine = new GenericCaptchaEngine(factories);

     instanceSound = new GenericManageableCaptchaService(captchaEngine, 180,180000, 75000);
     return instanceSound;
     }
}



//invoking servlet 
public class SoundCaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


/**
 * @see HttpServlet#HttpServlet()
 */
public SoundCaptchaServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    AudioInputStream audioCaptcha=null;
    try {
        String captchaId = request.getSession().getId();
        WordGenerator wordGen= new RandomWordGenerator("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzxyz0123456789");
        audioCaptcha=CustomSoundCaptchaServlet.getInstance(worGen).getSoundChallengeForID(captchaId);

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (CaptchaServiceException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("audio/mpeg");
    ServletOutputStream out = response.getOutputStream();
    ByteArrayOutputStream soundByteOutputStream = new ByteArrayOutputStream();
    AudioSystem.write(audioCaptcha,javax.sound.sampled.AudioFileFormat.Type.WAVE,soundByteOutputStream);
    out.write(soundByteOutputStream.toByteArray());
    out.flush();
    out.close();
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

//replace existing code in Voice.java with following
public void deallocate() {
setLoaded(false);
utteranceProcessors.clear();

    if (!externalAudioPlayer) {
        if (audioPlayer != null) {
            audioPlayer.close();
            audioPlayer = null;
        }
    }

if (!externalOutputQueue) {

}
}