文本到语音使用嵌入

本文关键字:语音 文本 | 更新日期: 2023-09-27 18:10:27

我有这个代码,它工作得很好,但我一直在努力如何让它输出一个wav文件,可以嵌入到页面中,而不是让用户下载和收听。非常感谢任何帮助。我想能够使用查询字符串直接调用文件,使其与验证码文本匹配。模型。InstanceData["Code"]是文本字符串形式的验证码。我似乎就是想不明白这个问题。谢谢!

private void _playBtn_Click(object sender, ImageClickEventArgs e)
{
    HttpContext context = HttpContext.Current;
    if (context == null || context.Response == null)
    {
        return;
    }
    context.Response.Clear();
    context.Response.AddHeader("content-disposition", "attachment; filename=" + "captcha.wav");
    context.Response.AddHeader("content-transfer-encoding", "binary");
    context.Response.ContentType = "audio/wav";
    SoundGenerator soundGenerator = new SoundGenerator(Model.InstanceData["Code"]);
    MemoryStream sound = new MemoryStream();
    // Write the sound to the response stream 
    soundGenerator.Sound.Save(sound, SoundFormatEnum.Wav);
    sound.WriteTo(context.Response.OutputStream);
}

文本到语音使用嵌入

基本上经过多次尝试后,解决方案比我想象的要简单一些。我创建了一个新的CaptchaPlayer。Aspx播放器在我的项目和后面的代码中使用这个:

 protected void Page_Load(object sender, EventArgs e)
    {
        PlayCaptchaSession();
    }
    private void PlayCaptchaSession()
    {
        object o = Session["captcha"];
        if (o != null)
        {
            HttpContext context = HttpContext.Current;
            if (context == null || context.Response == null)
            {
                return;
            }
            //context.Response.AddHeader("content-disposition", "inline; filename=" + "captcha.wav");
            context.Response.AddHeader("content-transfer-encoding", "binary");
            context.Response.ContentType = "audio/wav";
            SoundGenerator soundGenerator = new SoundGenerator(o as string);
            MemoryStream sound = new MemoryStream();
            // Write the sound to the response stream 
            soundGenerator.Sound.Save(sound, SoundFormatEnum.Wav);
            sound.WriteTo(context.Response.OutputStream);
        }
    }
}

之后,我可以添加嵌入到表单页

 <embed id='captchaAudio' width='1' height='1' enablejavascript='true' autostart='false' name='Verification code player' src='/CaptchaPlayer.aspx'>
                <noembed><a href='/CaptchaPlayer.aspx' title='Verification code wave audio file download'>Audio File</a></noembed>
                 <script type="text/javascript">
                 $(document).ready(function(){
                     $(".capLink").click(function () {
                         //alert(".click() called.");
                         document.getElementById('captchaAudio').Play();
                     });
                 });    
                </script>

这就成功了!