C#生成音频文件以及转换成需要的格式

花了三天才做出来这么个小东西,其中碰到了好多意向不到的问题与难题,直接看代码吧还是。其中需要DotNetSpeech.dll(生成因文件)和lame_enc.dll(用于音频格式的转换)两个类库,还需要一个lame.exe运行程序,这个也是为了音频格式的转换。刚开始写,写的可能有点乱,但是这些代码都是完全可以运行的,如有不合适的地方,谢谢各位大神的指导!我把用到的几个类库都打包了,有需要的可以下载,谢谢!


    /// 生成声音文件
    /// 要朗读的文本
    /// 生成声音文件的路径
    /// 生成声音文件的名称
    private void CreateFile(string text, string filePath, string fileName)
    {
        if (!Directory.Exists(filePath))
        Directory.CreateDirectory(filePath);
        SpVoice sv = new SpVoice();
        SpeechVoiceSpeakFlags SVSF = SpeechVoiceSpeakFlags.SVSFlagsAsync;
        SpeechStreamFileMode SSFM = SpeechStreamFileMode.SSFMCreateForWrite;
        SpFileStream SFS = new SpFileStream();
        sv.Rate = -5;
        //删除已经存在的音频文件
        if (File.Exists(filePath + fileName))
        {
            File.Delete(filePath + fileName);
        }


        //生成音频文件,用于唱标
        SFS.Open(filePath + fileName, SSFM, false);


        sv.AudioOutputStream = SFS;
        sv.Speak(text, SVSF);
        sv.WaitUntilDone(System.Threading.Timeout.Infinite);
        SFS.Close();
        //将wav格式的音频文件转换为mp3格式
        string outfile = "-b 32 --resample 22.05 -m m \"" + filePath + fileName + "\" \"" + filePath + fileName.Replace(".wav", ".mp3") + "\"";
        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
        psi.FileName = Server.MapPath("./SingOpenBidInfo/") + "lame.exe";
        psi.Arguments = outfile;
        psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
        System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
        //p.Exited = new EventHandler()
        p.WaitForExit();
        p.EnableRaisingEvents = true;


        //删除已经存在的音频文件
        if (File.Exists(filePath + fileName))
        {
            File.Delete(filePath + fileName);
        }
    }

调用的方法如下;

{

//生成音频文件

//绝对路劲
        CreateFile(context, "C:/SingOpenBidInfo/",  "lrh.wav");

//相对路径
        CreateFile(context, Server.MapPath("./SingOpenBidInfo/"), bidPackageID + ".wav");

}


猜你喜欢

转载自blog.csdn.net/coder_chen/article/details/48024525
今日推荐