using DevicesService.Common ;
using DevicesService.Devices ;
using Device.ApiModel.DocumentServerModels ;
using Device.Caller ;
using Device.IICCardReader ;
using Functions.FileExt ;
using IDevice.Model.RFIDReader ;
using NAudio.Wave ;
using Newtonsoft.Json ;
using System ;
using System.Collections.Generic ;
using System.Drawing ;
using System.Drawing.Printing ;
using System.Globalization ;
using System.IO ;
using System.Linq ;
using System.Net ;
using System.Net.Http ;
using System.Runtime.InteropServices ;
using System.Speech.Synthesis ;
using System.Text ;
using System.Threading.Tasks ;
using System.Threading ;
using static System . Net . Mime . MediaTypeNames ;
using System.Text.RegularExpressions ;
using DevicesService.Commen ;
using System.Numerics ;
using System.Web ;
using NAudio.Wave.SampleProviders ;
using System.Configuration ;
namespace DevicesService.Common
{
/// <summary>
/// 网页调用C#方法
/// </summary>
public class ScriptCallbackObject
{
public DeviceCaller deviceCaller = new DeviceCaller ( ) ;
public HScamera hScamera = new HScamera ( 0 , 0 , 1 ) ;
private static SpeechSynthesizer speech = new SpeechSynthesizer ( ) ;
//读取身份证
public string IDCardRead ( string paramsString , string callback )
{
Task . Run ( ( ) = >
GetCardInfo ( )
) ;
@event . WaitOne ( ) ;
string json = JsonConvert . SerializeObject ( resultModel ) ;
if ( resultModel . Code = = "1" )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":" + json + "}" ;
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + resultModel . Message + "\" } " ;
}
}
private ResultModel < RFIDDataModel > resultModel = null ;
private AutoResetEvent @event = new AutoResetEvent ( false ) ;
private async void GetCardInfo ( )
{
ICCardReadControl iCCard = new ICCardReadControl ( ) ;
resultModel = await iCCard . ReadIDCardData ( ) ;
@event . Set ( ) ;
}
/// <summary>
/// 打印排队票据
/// </summary>
/// <param name="ph">排号</param>
/// <param name="ddrs">等待人数</param>
/// <param name="qrcode">二维码</param>
/// <param name="ywmc">办理业务名称</param>
/// <returns></returns>
public string SendByPrint ( string ph , string ddrs , string qrcode , string ywmc , string callback )
{
try
{
Task < ResultModel > resultModel = deviceCaller . SendByPrint ( ph , ddrs , qrcode , ywmc ) ;
if ( resultModel . Result . Code = = "1" )
{
string json = JsonConvert . SerializeObject ( resultModel . Result ) ;
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":" + json + "}" ;
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + resultModel . Result . Message + "\"}" ;
}
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 文字语音播报
/// </summary>
/// <param name="centont"></param>
/// <param name="phone"></param>
/// <returns></returns>
public string payleText ( string text , bool ispaye , string callback )
{
try
{
if ( text . Length > 6 5 5 3 5 )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":" + "文字太长" + "}" ;
}
if ( ispaye )
{
speech . SpeakAsyncCancelAll ( ) ;
}
else
{
try
{
//if (text.Contains("http:"))
//{
// DateTime dateTime = DateTime.Now;
// string time = DateTime.Now.ToString(
// "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
// var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "TempFile");
// FileExt.MakeSureDirExist(dirpath);
// var filepath = Path.Combine(dirpath, time);
// string path = dirpath + "\\" + time + ".txt";
// WebRequest request = WebRequest.Create(text);
// WebResponse response = request.GetResponse();
// using (Stream stream = response.GetResponseStream())
// {
// using (FileStream fileStream = new FileStream(path, FileMode.Create))
// {
// stream.CopyTo(fileStream);
// }
// }
// response.Close();
// using (StreamReader sr = new StreamReader(path))
// {
// text = string.Empty;
// string line;
// while ((line = sr.ReadLine()) != null)
// {
// // 处理每一行数据
// text = text + line;
// }
// }
//}
Task . Run ( ( ) = >
{
text = text . Replace ( "(" , "" ) . Replace ( ")" , "、" ) ;
speech . Speak ( text ) ;
} ) ;
}
catch { }
}
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":" + "" + "}" ;
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 发送短信
/// </summary>
/// <param name="centont"></param>
/// <param name="phone"></param>
/// <returns></returns>
public string SendSSM ( string content , string phone , string callback )
{
try
{
Task < ResultModel > resultModel = deviceCaller . SendSSM ( content , phone ) ;
if ( resultModel . Result . Code = = "1" )
{
string json = JsonConvert . SerializeObject ( resultModel . Result ) ;
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":" + json + "}" ;
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":" + resultModel . Result . Message + "}" ;
}
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 打开高拍仪并且进行快速扫描文件
/// </summary>
/// <returns></returns>
public string openCamera ( string url , string callback )
{
try
{
string data = hScamera . openCamera2 ( ) ;
if ( ! string . IsNullOrEmpty ( data ) )
{
FileInfo fileInfo = new FileInfo ( data ) ;
//压缩
string newdata = Util . CompressPictures ( fileInfo ) ;
//转换
string base64 = Util . ImgToBase64String ( newdata ) ;
//Task.Run(async () =>
//{
// UploadInfoByFile(url, data);
//});
//@event5.WaitOne();
//Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#? (?:[\w]*))?)");
//MatchCollection mc = re.Matches(url);//获取的是一个数组
//string imgurl = mc[0].ToString() + "://" + mc[1].ToString() + urlP;
return base64 ;
}
else
{
data = hScamera . openCamera2 ( ) ;
if ( ! string . IsNullOrEmpty ( data ) )
{
string base64 = Util . ImgToBase64String ( data ) ;
//Task.Run(async () =>
//{
// UploadInfoByFile(url, data);
//});
//@event5.WaitOne();
//Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#? (?:[\w]*))?)");
//MatchCollection mc = re.Matches(url);//获取的是一个数组
//string imgurl = mc[0].ToString() + "://" + mc[1].ToString() + urlP;
return base64 ;
}
else
{
return Util . str2Base64 ( "400" ) ;
}
}
}
catch ( Exception ex )
{
Log . Info ( "扫描仪异常:" + ex . Message ) ;
return Util . str2Base64 ( "400" ) ;
}
}
/// <summary>
/// 打开签字版数据
/// </summary>
/// <returns></returns>
public string OpenSign ( string paramsString , string callback )
{
try
{
string sourcepaht = Environment . CurrentDirectory + "\\fiveInch.png" ;
FileInfo fileInfo = new FileInfo ( sourcepaht ) ;
if ( ! fileInfo . Exists )
{
int width = 8 0 0 ;
int height = 3 9 4 ;
using ( Bitmap blankImage = new Bitmap ( width , height ) )
{
// 设置图片背景为完全透明
using ( Graphics g = Graphics . FromImage ( blankImage ) )
{
// 使用白色背景填充图片
g . Clear ( Color . Transparent ) ;
}
// 保存图片到文件系统
blankImage . Save ( sourcepaht ) ;
}
}
int ret = SignDll . OpenComDevice ( ) ;
if ( ret = = 0 )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "开启签字版成功" + "\"}" ;
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "开启签字版失败" + "\"}" ;
}
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 关闭签字版数据
/// </summary>
/// <returns></returns>
public string CloseSign ( string paramsString , string callback )
{
try
{
int ret = SignDll . CloseComDevice ( ) ;
if ( ret = = 0 )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "关闭签字版成功" + "\"}" ;
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "关闭签字版失败" + "\"}" ;
}
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 获取签字版数据
/// </summary>
/// <returns></returns>
public string GetSignData ( string url , string callback )
{
try
{
string sourcepaht = Environment . CurrentDirectory + "\\fiveInch.png" ;
FileInfo fileInfo = new FileInfo ( sourcepaht ) ;
if ( fileInfo . Exists )
{
double size = fileInfo . Length / 1 0 2 4.0 ;
if ( size > 1 0 )
{
FileStream fs1 = fileInfo . OpenRead ( ) ;
fs1 . Close ( ) ;
//string base64 = Util.ConvertImageToBase64(sourcepaht);
Task . Run ( async ( ) = >
{
UploadInfoByFile ( url , sourcepaht ) ;
} ) ;
@event5 . WaitOne ( ) ;
File . Delete ( sourcepaht ) ;
int width = 8 0 0 ;
int height = 3 9 4 ;
using ( Bitmap blankImage = new Bitmap ( width , height ) )
{
// 设置图片背景为完全透明
using ( Graphics g = Graphics . FromImage ( blankImage ) )
{
// 使用白色背景填充图片
g . Clear ( Color . Transparent ) ;
}
// 保存图片到文件系统
blankImage . Save ( sourcepaht ) ;
}
Regex re = new Regex ( @"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#? (?:[\w]*))?)" ) ;
MatchCollection mc = re . Matches ( url ) ; //获取的是一个数组
string imgurl = mc [ 0 ] . ToString ( ) + "://" + mc [ 1 ] . ToString ( ) + urlP ;
//关闭签字版
//SignDll.CloseComDevice();
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + imgurl + "\"}" ;
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "用户未签字或签字不规范" + "\"}" ;
}
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "用户未签字或签字不规范" + "\"}" ;
}
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 根据文件地址在线打印
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public string PrintFile ( string url , string ext , string callback )
{
try
{
PrintDocument fPrintDocument = new PrintDocument ( ) ;
if ( string . IsNullOrEmpty ( fPrintDocument . PrinterSettings . PrinterName ) )
{
return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "请求设置默认打印机!" + "\"}" ;
}
Task . Run ( async ( ) = >
{
//DateTime dateTime = DateTime.Now;
//string time = DateTime.Now.ToString(
// "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
//var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "PrintFile");
//FileExt.MakeSureDirExist(dirpath);
//var filepath = Path.Combine(dirpath, time);
//string path = dirpath + "\\" + time + "." + ext;
//WebRequest request = WebRequest.Create(url);
//WebResponse response = request.GetResponse();
//using (Stream stream = response.GetResponseStream())
//{
// using (FileStream fileStream = new FileStream(path, FileMode.Create))
// {
// stream.CopyTo(fileStream);
// }
//}
//response.Close();
Util . Print2 ( url , fPrintDocument . PrinterSettings . PrinterName ) ;
} ) ;
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "打印成功" + "\"}" ;
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 根据文件base64打印
/// </summary>
/// <param name="base64"></param>
/// <param name="ext"></param>
/// <returns></returns>
public string PrintBase64 ( string base64 , string ext , string callback )
{
try
{
PrintDocument fPrintDocument = new PrintDocument ( ) ;
if ( string . IsNullOrEmpty ( fPrintDocument . PrinterSettings . PrinterName ) )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "请求设置默认打印机!" + "\"}" ;
}
Task . Run ( async ( ) = >
{
DateTime dateTime = DateTime . Now ;
string time = DateTime . Now . ToString (
"yyyyMMddHHmmss" , DateTimeFormatInfo . InvariantInfo ) ;
var dirpath = Path . Combine ( Environment . CurrentDirectory , "wwwroot" , "PrintFile" ) ;
FileExt . MakeSureDirExist ( dirpath ) ;
var filepath = Path . Combine ( dirpath , time ) ;
string path = dirpath + "\\" + time + "." + ext ;
byte [ ] bytes = Convert . FromBase64String ( base64 ) ;
System . IO . FileStream stream = new System . IO . FileStream ( path , System . IO . FileMode . CreateNew ) ;
System . IO . BinaryWriter writer = new System . IO . BinaryWriter ( stream ) ;
writer . Write ( bytes , 0 , bytes . Length ) ;
writer . Close ( ) ;
Util . Print2 ( path , fPrintDocument . PrinterSettings . PrinterName ) ;
} ) ;
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "打印成功" + "\"}" ;
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 发送com数据
/// </summary>
/// <returns></returns>
public string SendMsg ( string paramsString , string callback )
{
try
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "发送com数据" + "\"}" ;
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 开始录音
/// </summary>
/// <returns></returns>
public string SoundRecording ( bool isopen , string url , string callback )
{
try
{
Task < ResultModel > resultModel = SoundRecor ( isopen ) ;
if ( resultModel . Result . Code = = "1" )
{
//结束录音上传文件
if ( ! string . IsNullOrEmpty ( url ) & & ! isopen )
{
string filename = Path . GetFileName ( srpath ) ;
string path = ConfigurationManager . AppSettings [ "rootPath" ] . ToString ( ) ;
return path + "Record/" + filename ;
}
else if ( isopen ) //开始录音
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"wav\",\"data\":\"" + "开始录音" + "\"}" ;
}
else //取消录音
{
srpath = string . Empty ;
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"wav\",\"data\":\"" + "取消录音" + "\"}" ;
}
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + resultModel . Result . Message + "\"}" ;
}
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 播放与暂停
/// </summary>
/// <returns></returns>
public static NAudio . Wave . WaveOutEvent player = null ;
public static AudioFileReader audioFileReader = null ;
public static string WaveOutPath = string . Empty ;
public string Paly ( string url , bool ispaly , string callback )
{
try
{
if ( ispaly )
{
if ( player = = null )
{
NewMethod ( url ) ;
if ( player ! = null )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "音频播放" + "\"}" ;
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "未发现播放文件" + "\"}" ;
}
}
else
{
if ( string . IsNullOrEmpty ( url ) )
{
player . Play ( ) ;
Log . Info ( "恢复播放" ) ;
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "恢复播放" + "\"}" ;
}
else
{
if ( player . PlaybackState = = PlaybackState . Playing )
{
player . Stop ( ) ;
// 释放资源
player . Dispose ( ) ;
audioFileReader . Dispose ( ) ;
}
NewMethod ( url ) ;
if ( player ! = null )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "音频播放" + "\"}" ;
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "未发现播放文件" + "\"}" ;
}
}
}
}
else
{
if ( player ! = null )
{
if ( string . IsNullOrEmpty ( url ) )
{
player . Pause ( ) ;
Log . Info ( "暂停播放" ) ;
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "暂停播放" + "\"}" ;
}
else
{
player . Stop ( ) ;
// 释放资源
player . Dispose ( ) ;
audioFileReader . Dispose ( ) ;
player = null ;
File . Delete ( WaveOutPath ) ;
Log . Info ( "停止播放" ) ;
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "停止播放" + "\"}" ;
}
}
else
{
return "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "未发现播放文件" + "\"}" ;
}
}
}
catch ( Exception ex )
{
return "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex . Message + "\"}" ;
}
}
/// <summary>
/// 播放音频公共方法
/// </summary>
/// <param name="url"></param>
private void NewMethod ( string url )
{
//Uri uri = new Uri(url);
////返回 123.xlsx
//var filename = HttpUtility.UrlDecode(uri.Segments.Last());
////获取文件后缀
//string ext = Path.GetExtension(filename);
//DateTime dateTime = DateTime.Now;
//string time = DateTime.Now.ToString(
// "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
//var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "WaveOutFile");
//FileExt.MakeSureDirExist(dirpath);
//var filepath = Path.Combine(dirpath, time);
//WebRequest request = WebRequest.Create(url);
//WebResponse response = request.GetResponse();
//using (Stream stream = response.GetResponseStream())
//{
// using (FileStream fileStream = new FileStream(WaveOutPath, FileMode.Create))
// {
// stream.CopyTo(fileStream);
// }
//}
//response.Close();
WaveOutPath = url ;
using ( player = new WaveOutEvent ( ) )
{
player . PlaybackStopped + = waveOut_PlaybackStopped ;
using ( audioFileReader = new AudioFileReader ( WaveOutPath ) )
{
// 创建一个增益效果器对象
var volumeProvider = new VolumeSampleProvider ( audioFileReader . ToSampleProvider ( ) ) ;
// 将音频文件添加到WaveOutEvent对象中
player . Init ( volumeProvider ) ;
// 设置音量增益为2倍
volumeProvider . Volume = 2.0f ;
// 开始播放音频
player . Play ( ) ;
while ( player . PlaybackState = = PlaybackState . Playing )
{
Thread . Sleep ( 1 0 0 0 ) ;
}
}
}
Log . Info ( "开始播放" ) ;
}
/// <summary>
/// 播放完成
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void waveOut_PlaybackStopped ( object sender , StoppedEventArgs e )
{
try
{
player . Stop ( ) ;
// 释放资源
player . Dispose ( ) ;
audioFileReader . Dispose ( ) ;
player = null ;
File . Delete ( WaveOutPath ) ;
Log . Info ( "播放完成" ) ;
}
catch ( Exception ex )
{
Log . Info ( "播放完成,清除本地文件异常" + ex . Message ) ;
}
}
//上传本地文件中转
private string urlP = string . Empty ;
private AutoResetEvent @event5 = new AutoResetEvent ( false ) ;
private async void UploadInfoByFile ( string url , string strpath )
{
var httpClient = new HttpClient ( ) ;
var uploader = new ChunkedUpload ( httpClient ) ;
urlP = await uploader . UploadFileAsync ( url , strpath ) ;
File . Delete ( strpath ) ;
@event5 . Set ( ) ;
}
//上传录音
private string urlpath = string . Empty ;
private AutoResetEvent @event2 = new AutoResetEvent ( false ) ;
private async void UploadInfo ( string url )
{
var httpClient = new HttpClient ( ) ;
var uploader = new ChunkedUpload ( httpClient ) ;
urlpath = await uploader . UploadFileAsync ( url , srpath ) ;
//File.Delete(srpath);
srpath = string . Empty ;
@event2 . Set ( ) ;
}
public static WaveFileWriter writer ;
public static StreamWriter mStreamWriter ;
public static WaveInEvent waveIn = null ;
private string srpath = string . Empty ;
private AutoResetEvent @event3 = new AutoResetEvent ( false ) ;
private void StateSoundRecor ( bool isopen )
{
// 录音对象
waveIn = new WaveInEvent ( ) ;
int sampleRate = 4 8 0 0 0 ; //采样率
int channels = 2 ; //录音通道数
int bitsPerSample = 1 6 ; //位深
WaveFormat waveFormat = new WaveFormat ( sampleRate , bitsPerSample , channels ) ;
waveIn . WaveFormat = waveFormat ; //设置录音格式
DateTime dateTime = DateTime . Now ;
string time = DateTime . Now . ToString (
"yyyyMMddHHmmss" , DateTimeFormatInfo . InvariantInfo ) ;
var dirpath = System . IO . Path . Combine ( Environment . CurrentDirectory , "wwwroot" , "Record" ) ;
FileExt . MakeSureDirExist ( dirpath ) ;
var filepath = System . IO . Path . Combine ( dirpath , time ) ;
srpath = dirpath + "\\" + time + ".wav" ;
string pathfile = dirpath + "\\" + time + ".txt" ;
// 创建WaveFileWriter对象来保存录音数据 路径在bin文件下
writer = new WaveFileWriter ( srpath , waveFormat ) ;
//编写器
//mStreamWriter = new StreamWriter(pathfile, false, new System.Text.UTF8Encoding(false));
// 设置录音回调函数
int bitIndex = bitsPerSample / 8 ;
waveIn . DataAvailable + = ( sender , e ) = >
{
// 将录音数据写入文件
writer . Write ( e . Buffer , 0 , e . BytesRecorded ) ;
for ( int i = 0 ; i < e . BytesRecorded / bitIndex ; i + + )
{
//24bit,导出的数据
//int sample = (int)((e.Buffer[i * bitIndex + 2] << 16) | (e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]);
//16bit 将两个byte数据组合成一个short数据
short sample = ( short ) ( ( e . Buffer [ i * bitIndex + 1 ] < < 8 ) | e . Buffer [ i * bitIndex ] ) ;
//mStreamWriter.Write("{0},", sample);
}
} ;
try
{
//尝试打开录音设备,如果设备支持设置的WaveFormat,则能够成功打开
waveIn . StartRecording ( ) ;
}
catch ( Exception ex )
{
srpath = "" ;
}
//@event3.Set();
}
private AutoResetEvent @event4 = new AutoResetEvent ( false ) ;
private async void StopSoundRecor ( bool isopen )
{
try
{
//停止录音
waveIn . StopRecording ( ) ;
waveIn . Dispose ( ) ;
writer . Close ( ) ;
//mStreamWriter.Close();
waveIn = null ;
}
catch ( Exception ex )
{
srpath = "" ;
}
//@event4.Set();
}
public async Task < ResultModel > SoundRecor ( bool isopen )
{
if ( isopen )
{
//如果开始录音上次未结束,直接结束上次录音,开始新的录音
if ( waveIn ! = null )
{
StopSoundRecor ( false ) ;
}
if ( waveIn = = null )
{
Action < bool > a = StateSoundRecor ;
a . Invoke ( isopen ) ;
//Task.Run(() =>
//{
// StateSoundRecor();
//});
//@event3.WaitOne();
if ( ! string . IsNullOrEmpty ( srpath ) ) { return ResultModel . Success ( srpath ) ; }
else { return ResultModel . Error ( "录音开启失败" ) ; }
}
else
{
return ResultModel . Error ( "正在录音,请勿重复录音" ) ;
}
}
else
{
try
{
if ( waveIn ! = null )
{
//Task.Run(() =>
//{
// StopSoundRecor();
//});
//@event4.WaitOne();
Action < bool > a = StopSoundRecor ;
a . Invoke ( isopen ) ;
if ( ! string . IsNullOrEmpty ( srpath ) ) { return ResultModel . Success ( srpath ) ; }
else { return ResultModel . Error ( "录音停止失败" ) ; }
}
else
{
return ResultModel . Error ( "未开始录音" ) ;
}
}
catch ( Exception ex )
{
return ResultModel . Error ( ex . Message ) ;
}
}
}
}
}