如果您对使用C#9的records作为强类型ID-路由和查询参数和c#强类型和弱类型感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解使用C#9的records作为强类型ID-路由和查询参数的各种
如果您对使用 C# 9 的 records 作为强类型 ID - 路由和查询参数和c#强类型和弱类型感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解使用 C# 9 的 records 作为强类型 ID - 路由和查询参数的各种细节,并对c#强类型和弱类型进行深入的分析,此外还有关于标签的coords里面的值怎么根据图片大小改变,自动获取?、android-如何使用setMaxDuration限制AudioRecord作为MediaRecorder的录制时间、Android录音--AudioRecord、MediaRecorder的使用、angular6 路由拼接查询参数如 ?id=1 并获取url参数的实用技巧。
本文目录一览:- 使用 C# 9 的 records 作为强类型 ID - 路由和查询参数(c#强类型和弱类型)
- 标签的coords里面的值怎么根据图片大小改变,自动获取?">标签的coords里面的值怎么根据图片大小改变,自动获取?
- android-如何使用setMaxDuration限制AudioRecord作为MediaRecorder的录制时间
- Android录音--AudioRecord、MediaRecorder的使用
- angular6 路由拼接查询参数如 ?id=1 并获取url参数
使用 C# 9 的 records 作为强类型 ID - 路由和查询参数(c#强类型和弱类型)
上一篇文章,我介绍了使用 C# 9 的 record 类型作为强类型 id,非常简洁
public record ProductId(int Value);
但是在强类型 id 真正可用之前,还有一些问题需要解决,比如,ASP.NET Core 并不知道如何在路由参数或查询字符串参数中正确的处理它们,在这篇文章中,我将展示如何解决这个问题。
路由和查询字符串参数的模型绑定
假设我们有一个这样的实体:
public record ProductId(int Value);
public class Product
{
public ProductId Id { get; set; }
public string Name { get; set; }
public decimal UnitPrice { get; set; }
}
和这样的 API 接口:
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
...
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(ProductId id)
{
return Ok(new Product {
Id = id,
Name = "Apple",
UnitPrice = 0.8M
});
}
}
现在,我们尝试用 Get 方式访问这个接口 /api/product/1
:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "00-3600640f4e053b43b5ccefabe7eebd5a-159f5ca18d189142-00"
}
现在问题就来了,返回了 415,.NET Core 不知道怎么把 URL 的参数转换为 ProductId,由于它不是 int,是我们定义的强类型 ID,并且没有关联的类型转换器。
实现类型转换器
这里的解决方案是为实现一个类型转换器 ProductId,很简单:
public class ProductIdConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) =>
sourceType == typeof(string);
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) =>
destinationType == typeof(string);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return value switch
{
string s => new ProductId(int.Parse(s)),
null => null,
_ => throw new ArgumentException($"Cannot convert from {value} to ProductId", nameof(value))
};
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
return value switch
{
ProductId id => id.Value.ToString(),
null => null,
_ => throw new ArgumentException($"Cannot convert {value} to string", nameof(value))
};
}
throw new ArgumentException($"Cannot convert {value ?? "(null)"} to {destinationType}", nameof(destinationType));
}
}
(请注意,为简洁起见,我只处理并转换 string, 在实际情况下,我们可能还希望支持转换 int)
我们的 ProductId 使用 TypeConverter 特性将该转换器与记录相关联:
[TypeConverter(typeof(ProductIdConverter))]
public record ProductId(int Value);
现在,让我们尝试再次访问这个接口:
{
"id": {
"value": 1
},
"name": "Apple",
"unitPrice": 0.8
}
现在是返回了,但是还有点问题,id 在 json 中显示了一个对象,如何在 json 中处理,是我们下一篇文章给大家介绍的,现在还有一点是,我上面写了一个 ProductId 的转换器,但是如果我们的类型足够多,那也有很多工作量,所以需要一个公共的通用转换器。
通用强类型 id 转换器
首先,让我们创建一个 Helper
• 检查类型是否为强类型 ID,并获取值的类型 • 获取值得类型,创建并缓存一个委托
public static class StronglyTypedIdHelper
{
private static readonly ConcurrentDictionary<Type, Delegate> StronglyTypedIdFactories = new();
public static Func<TValue, object> GetFactory<TValue>(Type stronglyTypedIdType)
where TValue : notnull
{
return (Func<TValue, object>)StronglyTypedIdFactories.GetOrAdd(
stronglyTypedIdType,
CreateFactory<TValue>);
}
private static Func<TValue, object> CreateFactory<TValue>(Type stronglyTypedIdType)
where TValue : notnull
{
if (!IsStronglyTypedId(stronglyTypedIdType))
throw new ArgumentException($"Type ''{stronglyTypedIdType}'' is not a strongly-typed id type", nameof(stronglyTypedIdType));
var ctor = stronglyTypedIdType.GetConstructor(new[] { typeof(TValue) });
if (ctor is null)
throw new ArgumentException($"Type ''{stronglyTypedIdType}'' doesn''t have a constructor with one parameter of type ''{typeof(TValue)}''", nameof(stronglyTypedIdType));
var param = Expression.Parameter(typeof(TValue), "value");
var body = Expression.New(ctor, param);
var lambda = Expression.Lambda<Func<TValue, object>>(body, param);
return lambda.Compile();
}
public static bool IsStronglyTypedId(Type type) => IsStronglyTypedId(type, out _);
public static bool IsStronglyTypedId(Type type, [NotNullWhen(true)] out Type idType)
{
if (type is null)
throw new ArgumentNullException(nameof(type));
if (type.BaseType is Type baseType &&
baseType.IsGenericType &&
baseType.GetGenericTypeDefinition() == typeof(StronglyTypedId<>))
{
idType = baseType.GetGenericArguments()[0];
return true;
}
idType = null;
return false;
}
}
这个 Helper 帮助我们编写类型转换器,现在,我们可以编写通用转换器了。
public class StronglyTypedIdConverter<TValue> : TypeConverter
where TValue : notnull
{
private static readonly TypeConverter IdValueConverter = GetIdValueConverter();
private static TypeConverter GetIdValueConverter()
{
var converter = TypeDescriptor.GetConverter(typeof(TValue));
if (!converter.CanConvertFrom(typeof(string)))
throw new InvalidOperationException(
$"Type ''{typeof(TValue)}'' doesn''t have a converter that can convert from string");
return converter;
}
private readonly Type _type;
public StronglyTypedIdConverter(Type type)
{
_type = type;
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string)
|| sourceType == typeof(TValue)
|| base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string)
|| destinationType == typeof(TValue)
|| base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string s)
{
value = IdValueConverter.ConvertFrom(s);
}
if (value is TValue idValue)
{
var factory = StronglyTypedIdHelper.GetFactory<TValue>(_type);
return factory(idValue);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is null)
throw new ArgumentNullException(nameof(value));
var stronglyTypedId = (StronglyTypedId<TValue>)value;
TValue idValue = stronglyTypedId.Value;
if (destinationType == typeof(string))
return idValue.ToString()!;
if (destinationType == typeof(TValue))
return idValue;
return base.ConvertTo(context, culture, value, destinationType);
}
}
然后再创建一个非泛型的 Converter
public class StronglyTypedIdConverter : TypeConverter
{
private static readonly ConcurrentDictionary<Type, TypeConverter> ActualConverters = new();
private readonly TypeConverter _innerConverter;
public StronglyTypedIdConverter(Type stronglyTypedIdType)
{
_innerConverter = ActualConverters.GetOrAdd(stronglyTypedIdType, CreateActualConverter);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) =>
_innerConverter.CanConvertFrom(context, sourceType);
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) =>
_innerConverter.CanConvertTo(context, destinationType);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) =>
_innerConverter.ConvertFrom(context, culture, value);
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) =>
_innerConverter.ConvertTo(context, culture, value, destinationType);
private static TypeConverter CreateActualConverter(Type stronglyTypedIdType)
{
if (!StronglyTypedIdHelper.IsStronglyTypedId(stronglyTypedIdType, out var idType))
throw new InvalidOperationException($"The type ''{stronglyTypedIdType}'' is not a strongly typed id");
var actualConverterType = typeof(StronglyTypedIdConverter<>).MakeGenericType(idType);
return (TypeConverter)Activator.CreateInstance(actualConverterType, stronglyTypedIdType)!;
}
}
到这里,我们可以直接删除之前的 ProductIdConvert, 现在有一个通用的可以使用,现在.NET Core 的路由匹配已经没有问题了,接下来的文章,我会介绍如何处理在 JSON 中出现的问题。
[TypeConverter(typeof(StronglyTypedIdConverter))]
public abstract record StronglyTypedId<TValue>(TValue Value)
where TValue : notnull
{
public override string ToString() => Value.ToString();
}
原文作者: thomas levesque 原文链接:https://thomaslevesque.com/2020/11/23/csharp-9-records-as-strongly-typed-ids-part-2-aspnet-core-route-and-query-parameters/
最后
欢迎扫码关注我们的公众号 【全球技术精选】,专注国外优秀博客的翻译和开源项目分享,也可以添加 QQ 群 897216102
本文分享自微信公众号 - dotNET 跨平台(opendotnet)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与 “OSC 源创计划”,欢迎正在阅读的你也加入,一起分享。
标签的coords里面的值怎么根据图片大小改变,自动获取?" alt="标签的coords里面的值怎么根据图片大小改变,自动获取?">
标签的coords里面的值怎么根据图片大小改变,自动获取?">标签的coords里面的值怎么根据图片大小改变,自动获取?
我用<img /> <area/>映射热区,要获取几个矩形热区做链接,图片自适应,但是里面coords的值怎么根据浏览器屏幕大小的改变,coords的值也跟着改变啊?不要写死的值。JS怎么写啊?我弄了两天啦,还是没完全弄出来,能不能写下具体实现动态获取coords值的JS代码啊?
android-如何使用setMaxDuration限制AudioRecord作为MediaRecorder的录制时间
从开始时间起2分钟后,我需要停止AudioRecord.
使用MediaRecorder时,我可以使用setMaxDuration,并且效果很好,但是我也需要AudioRecord的一种好方法.
感谢帮助
解决方法:
你可以这样尝试
handler=new Handler();
Runnable r=new Runnable()
{
public void run()
{
recorder.stop();
recorder.release();
}
};
handler.postDelayed(r, 120000);
Android录音--AudioRecord、MediaRecorder的使用
Android提供了两个API用于实现录音功能:android.media.AudioRecord、android.media.MediaRecorder。
网上有很多谈论这两个类的资料。现在大致总结下:
1、AudioRecord
主要是实现边录边播(AudioRecord+AudioTrack)以及对音频的实时处理(如会说话的汤姆猫、语音)
优点:语音的实时处理,可以用代码实现各种音频的封装
缺点:输出是PCM语音数据,如果保存成音频文件,是不能够被播放器播放的,所以必须先写代码实现数据编码以及压缩
示例:
使用AudioRecord类录音,并实现WAV格式封装。录音20s,输出的音频文件大概为3.5M左右(已写测试代码)
2、MediaRecorder
已经集成了录音、编码、压缩等,支持少量的录音音频格式,大概有.aac(API = 16) .amr .3gp
优点:大部分以及集成,直接调用相关接口即可,代码量小
缺点:无法实时处理音频;输出的音频格式不是很多,例如没有输出mp3格式文件
示例:
使用MediaRecorder类录音,输出amr格式文件。录音20s,输出的音频文件大概为33K(已写测试代码)
3、音频格式比较
WAV格式:录音质量高,但是压缩率小,文件大
AAC格式:相对于mp3,AAC格式的音质更佳,文件更小;有损压缩;一般苹果或者Android SDK4.1.2(API 16)及以上版本支持播放
AMR格式:压缩比比较大,但相对其他的压缩格式质量比较差,多用于人声,通话录音
至于常用的mp3格式,使用MediaRecorder没有该视频格式输出。一些人的做法是使用AudioRecord录音,然后编码成wav格式,再转换成mp3格式
再贴上一些测试工程。
功能描述:
1、点击“录音WAV文件”,开始录音。录音完成后,生成文件/sdcard/FinalAudio.wav
2、点击“录音AMR文件”,开始录音。录音完成后,生成文件/sdcard/FinalAudio.amr
3、点击“停止录音”,停止录音,并显示录音输出文件以及该文件大小。
大致代码如下:
1、AudioRecord录音,封装成WAV格式
package com.example.audiorecordtest; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.media.AudioFormat; import android.media.AudioRecord; public class AudioRecordFunc { // 缓冲区字节大小 private int bufferSizeInBytes = 0; //AudioName裸音频数据文件 ,麦克风 private String AudioName = ""; //NewAudioName可播放的音频文件 private String NewAudioName = ""; private AudioRecord audioRecord; private boolean isRecord = false;// 设置正在录制的状态 private static AudioRecordFunc mInstance; private AudioRecordFunc(){ } public synchronized static AudioRecordFunc getInstance() { if(mInstance == null) mInstance = new AudioRecordFunc(); return mInstance; } public int startRecordAndFile() { //判断是否有外部存储设备sdcard if(AudioFileFunc.isSdcardExit()) { if(isRecord) { return ErrorCode.E_STATE_RECODING; } else { if(audioRecord == null) creatAudioRecord(); audioRecord.startRecording(); // 让录制状态为true isRecord = true; // 开启音频文件写入线程 new Thread(new AudioRecordThread()).start(); return ErrorCode.SUCCESS; } } else { return ErrorCode.E_NOSDCARD; } } public void stopRecordAndFile() { close(); } public long getRecordFileSize(){ return AudioFileFunc.getFileSize(NewAudioName); } private void close() { if (audioRecord != null) { System.out.println("stopRecord"); isRecord = false;//停止文件写入 audioRecord.stop(); audioRecord.release();//释放资源 audioRecord = null; } } private void creatAudioRecord() { // 获取音频文件路径 AudioName = AudioFileFunc.getRawFilePath(); NewAudioName = AudioFileFunc.getWavFilePath(); // 获得缓冲区字节大小 bufferSizeInBytes = AudioRecord.getMinBufferSize(AudioFileFunc.AUdio_SAMPLE_RATE,AudioFormat.CHANNEL_IN_STEREO,AudioFormat.ENCODING_PCM_16BIT); // 创建AudioRecord对象 audioRecord = new AudioRecord(AudioFileFunc.AUdio_INPUT,AudioFileFunc.AUdio_SAMPLE_RATE,AudioFormat.ENCODING_PCM_16BIT,bufferSizeInBytes); } class AudioRecordThread implements Runnable { @Override public void run() { writeDatetoFile();//往文件中写入裸数据 copyWaveFile(AudioName,NewAudioName);//给裸数据加上头文件 } } /** * 这里将数据写入文件,但是并不能播放,因为AudioRecord获得的音频是原始的裸音频, * 如果需要播放就必须加入一些格式或者编码的头信息。但是这样的好处就是你可以对音频的 裸数据进行处理,比如你要做一个爱说话的TOM * 猫在这里就进行音频的处理,然后重新封装 所以说这样得到的音频比较容易做一些音频的处理。 */ private void writeDatetoFile() { // new一个byte数组用来存一些字节数据,大小为缓冲区大小 byte[] audiodata = new byte[bufferSizeInBytes]; FileOutputStream fos = null; int readsize = 0; try { File file = new File(AudioName); if (file.exists()) { file.delete(); } fos = new FileOutputStream(file);// 建立一个可存取字节的文件 } catch (Exception e) { e.printstacktrace(); } while (isRecord == true) { readsize = audioRecord.read(audiodata,bufferSizeInBytes); if (AudioRecord.ERROR_INVALID_OPERATION != readsize && fos!=null) { try { fos.write(audiodata); } catch (IOException e) { e.printstacktrace(); } } } try { if(fos != null) fos.close();// 关闭写入流 } catch (IOException e) { e.printstacktrace(); } } // 这里得到可播放的音频文件 private void copyWaveFile(String inFilename,String outFilename) { FileInputStream in = null; FileOutputStream out = null; long totalAudioLen = 0; long totalDataLen = totalAudioLen + 36; long longSampleRate = AudioFileFunc.AUdio_SAMPLE_RATE; int channels = 2; long byterate = 16 * AudioFileFunc.AUdio_SAMPLE_RATE * channels / 8; byte[] data = new byte[bufferSizeInBytes]; try { in = new FileInputStream(inFilename); out = new FileOutputStream(outFilename); totalAudioLen = in.getChannel().size(); totalDataLen = totalAudioLen + 36; WriteWaveFileHeader(out,totalAudioLen,totalDataLen,longSampleRate,channels,byterate); while (in.read(data) != -1) { out.write(data); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printstacktrace(); } catch (IOException e) { e.printstacktrace(); } } /** * 这里提供一个头信息。插入这些信息就可以得到可以播放的文件。 * 为我为啥插入这44个字节,这个还真没深入研究,不过你随便打开一个wav * 音频的文件,可以发现前面的头文件可以说基本一样哦。每种格式的文件都有 * 自己特有的头文件。 */ private void WriteWaveFileHeader(FileOutputStream out,long totalAudioLen,long totalDataLen,long longSampleRate,int channels,long byterate) throws IOException { byte[] header = new byte[44]; header[0] = 'R'; // RIFF/WAVE header header[1] = 'I'; header[2] = 'F'; header[3] = 'F'; header[4] = (byte) (totalDataLen & 0xff); header[5] = (byte) ((totalDataLen >> 8) & 0xff); header[6] = (byte) ((totalDataLen >> 16) & 0xff); header[7] = (byte) ((totalDataLen >> 24) & 0xff); header[8] = 'W'; header[9] = 'A'; header[10] = 'V'; header[11] = 'E'; header[12] = 'f'; // 'fmt ' chunk header[13] = 'm'; header[14] = 't'; header[15] = ' '; header[16] = 16; // 4 bytes: size of 'fmt ' chunk header[17] = 0; header[18] = 0; header[19] = 0; header[20] = 1; // format = 1 header[21] = 0; header[22] = (byte) channels; header[23] = 0; header[24] = (byte) (longSampleRate & 0xff); header[25] = (byte) ((longSampleRate >> 8) & 0xff); header[26] = (byte) ((longSampleRate >> 16) & 0xff); header[27] = (byte) ((longSampleRate >> 24) & 0xff); header[28] = (byte) (byterate & 0xff); header[29] = (byte) ((byterate >> 8) & 0xff); header[30] = (byte) ((byterate >> 16) & 0xff); header[31] = (byte) ((byterate >> 24) & 0xff); header[32] = (byte) (2 * 16 / 8); // block align header[33] = 0; header[34] = 16; // bits per sample header[35] = 0; header[36] = 'd'; header[37] = 'a'; header[38] = 't'; header[39] = 'a'; header[40] = (byte) (totalAudioLen & 0xff); header[41] = (byte) ((totalAudioLen >> 8) & 0xff); header[42] = (byte) ((totalAudioLen >> 16) & 0xff); header[43] = (byte) ((totalAudioLen >> 24) & 0xff); out.write(header,44); } }
2、MediaRecorder录音,输出amr格式音频
package com.example.audiorecordtest; import java.io.File; import java.io.IOException; import android.media.MediaRecorder; public class MediaRecordFunc { private boolean isRecord = false; private MediaRecorder mMediaRecorder; private MediaRecordFunc(){ } private static MediaRecordFunc mInstance; public synchronized static MediaRecordFunc getInstance(){ if(mInstance == null) mInstance = new MediaRecordFunc(); return mInstance; } public int startRecordAndFile(){ //判断是否有外部存储设备sdcard if(AudioFileFunc.isSdcardExit()) { if(isRecord) { return ErrorCode.E_STATE_RECODING; } else { if(mMediaRecorder == null) createMediaRecord(); try{ mMediaRecorder.prepare(); mMediaRecorder.start(); // 让录制状态为true isRecord = true; return ErrorCode.SUCCESS; }catch(IOException ex){ ex.printstacktrace(); return ErrorCode.E_UNKOWN; } } } else { return ErrorCode.E_NOSDCARD; } } public void stopRecordAndFile(){ close(); } public long getRecordFileSize(){ return AudioFileFunc.getFileSize(AudioFileFunc.getAMRFilePath()); } private void createMediaRecord(){ /* ①Initial:实例化MediaRecorder对象 */ mMediaRecorder = new MediaRecorder(); /* setAudioSource/setVedioSource*/ mMediaRecorder.setAudioSource(AudioFileFunc.AUdio_INPUT);//设置麦克风 /* 设置输出文件的格式:THREE_GPP/MPEG-4/RAW_AMR/Default * THREE_GPP(3gp格式,H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB) */ mMediaRecorder.setoutputFormat(MediaRecorder.OutputFormat.DEFAULT); /* 设置音频文件的编码:AAC/AMR_NB/AMR_MB/Default */ mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); /* 设置输出文件的路径 */ File file = new File(AudioFileFunc.getAMRFilePath()); if (file.exists()) { file.delete(); } mMediaRecorder.setoutputFile(AudioFileFunc.getAMRFilePath()); } private void close(){ if (mMediaRecorder != null) { System.out.println("stopRecord"); isRecord = false; mMediaRecorder.stop(); mMediaRecorder.release(); mMediaRecorder = null; } } }
3、其他文件
AudioFileFunc.java
package com.example.audiorecordtest; import java.io.File; import android.media.MediaRecorder; import android.os.Environment; public class AudioFileFunc { //音频输入-麦克风 public final static int AUdio_INPUT = MediaRecorder.AudioSource.MIC; //采用频率 //44100是目前的标准,但是某些设备仍然支持22050,16000,11025 public final static int AUdio_SAMPLE_RATE = 44100; //44.1KHz,普遍使用的频率 //录音输出文件 private final static String AUdio_RAW_FILENAME = "RawAudio.raw"; private final static String AUdio_WAV_FILENAME = "FinalAudio.wav"; public final static String AUdio_AMR_FILENAME = "FinalAudio.amr"; /** * 判断是否有外部存储设备sdcard * @return true | false */ public static boolean isSdcardExit(){ if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) return true; else return false; } /** * 获取麦克风输入的原始音频流文件路径 * @return */ public static String getRawFilePath(){ String mAudioRawPath = ""; if(isSdcardExit()){ String fileBasePath = Environment.getExternalStorageDirectory().getAbsolutePath(); mAudioRawPath = fileBasePath+"/"+AUdio_RAW_FILENAME; } return mAudioRawPath; } /** * 获取编码后的WAV格式音频文件路径 * @return */ public static String getWavFilePath(){ String mAudioWavPath = ""; if(isSdcardExit()){ String fileBasePath = Environment.getExternalStorageDirectory().getAbsolutePath(); mAudioWavPath = fileBasePath+"/"+AUdio_WAV_FILENAME; } return mAudioWavPath; } /** * 获取编码后的AMR格式音频文件路径 * @return */ public static String getAMRFilePath(){ String mAudioAMRPath = ""; if(isSdcardExit()){ String fileBasePath = Environment.getExternalStorageDirectory().getAbsolutePath(); mAudioAMRPath = fileBasePath+"/"+AUdio_AMR_FILENAME; } return mAudioAMRPath; } /** * 获取文件大小 * @param path,文件的绝对路径 * @return */ public static long getFileSize(String path){ File mFile = new File(path); if(!mFile.exists()) return -1; return mFile.length(); } }
4、其他文件
ErrorCode.java
package com.example.audiorecordtest; import android.content.Context; import android.content.res.Resources.NotFoundException; public class ErrorCode { public final static int SUCCESS = 1000; public final static int E_NOSDCARD = 1001; public final static int E_STATE_RECODING = 1002; public final static int E_UNKOWN = 1003; public static String getErrorInfo(Context vContext,int vType) throws NotFoundException { switch(vType) { case SUCCESS: return "success"; case E_NOSDCARD: return vContext.getResources().getString(R.string.error_no_sdcard); case E_STATE_RECODING: return vContext.getResources().getString(R.string.error_state_record); case E_UNKOWN: default: return vContext.getResources().getString(R.string.error_unkNown); } } }
5、string.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">AudioRecordTest</string> <string name="hello_world">测试AudioRecord,实现录音功能</string> <string name="menu_settings">Settings</string> <string name="view_record_wav">录音WAV文件</string> <string name="view_record_amr">录音AMR文件</string> <string name="view_stop">停止录音</string> <string name="error_no_sdcard">没有SD卡,无法存储录音数据</string> <string name="error_state_record">正在录音中,请先停止录音</string> <string name="error_unkNown">无法识别的错误</string> </resources>
6、主程序MainActivity
package com.example.audiorecordtest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private final static int FLAG_WAV = 0; private final static int FLAG_AMR = 1; private int mState = -1; //-1:没再录制,0:录制wav,1:录制amr private Button btn_record_wav; private Button btn_record_amr; private Button btn_stop; private TextView txt; private UIHandler uiHandler; private UIThread uiThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewByIds(); setListeners(); init(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main,menu); return true; } private void findViewByIds(){ btn_record_wav = (Button)this.findViewById(R.id.btn_record_wav); btn_record_amr = (Button)this.findViewById(R.id.btn_record_amr); btn_stop = (Button)this.findViewById(R.id.btn_stop); txt = (TextView)this.findViewById(R.id.text); } private void setListeners(){ btn_record_wav.setonClickListener(btn_record_wav_clickListener); btn_record_amr.setonClickListener(btn_record_amr_clickListener); btn_stop.setonClickListener(btn_stop_clickListener); } private void init(){ uiHandler = new UIHandler(); } private Button.OnClickListener btn_record_wav_clickListener = new Button.OnClickListener(){ public void onClick(View v){ record(FLAG_WAV); } }; private Button.OnClickListener btn_record_amr_clickListener = new Button.OnClickListener(){ public void onClick(View v){ record(FLAG_AMR); } }; private Button.OnClickListener btn_stop_clickListener = new Button.OnClickListener(){ public void onClick(View v){ stop(); } }; /** * 开始录音 * @param mFlag,0:录制wav格式,1:录音amr格式 */ private void record(int mFlag){ if(mState != -1){ Message msg = new Message(); Bundle b = new Bundle();// 存放数据 b.putInt("cmd",CMD_RECORDFAIL); b.putInt("msg",ErrorCode.E_STATE_RECODING); msg.setData(b); uiHandler.sendMessage(msg); // 向Handler发送消息,更新UI return; } int mResult = -1; switch(mFlag){ case FLAG_WAV: AudioRecordFunc mRecord_1 = AudioRecordFunc.getInstance(); mResult = mRecord_1.startRecordAndFile(); break; case FLAG_AMR: MediaRecordFunc mRecord_2 = MediaRecordFunc.getInstance(); mResult = mRecord_2.startRecordAndFile(); break; } if(mResult == ErrorCode.SUCCESS){ uiThread = new UIThread(); new Thread(uiThread).start(); mState = mFlag; }else{ Message msg = new Message(); Bundle b = new Bundle();// 存放数据 b.putInt("cmd",mResult); msg.setData(b); uiHandler.sendMessage(msg); // 向Handler发送消息,更新UI } } /** * 停止录音 */ private void stop(){ if(mState != -1){ switch(mState){ case FLAG_WAV: AudioRecordFunc mRecord_1 = AudioRecordFunc.getInstance(); mRecord_1.stopRecordAndFile(); break; case FLAG_AMR: MediaRecordFunc mRecord_2 = MediaRecordFunc.getInstance(); mRecord_2.stopRecordAndFile(); break; } if(uiThread != null){ uiThread.stopThread(); } if(uiHandler != null) uiHandler.removeCallbacks(uiThread); Message msg = new Message(); Bundle b = new Bundle();// 存放数据 b.putInt("cmd",CMD_STOP); b.putInt("msg",mState); msg.setData(b); uiHandler.sendMessageDelayed(msg,1000); // 向Handler发送消息,更新UI mState = -1; } } private final static int CMD_RECORDING_TIME = 2000; private final static int CMD_RECORDFAIL = 2001; private final static int CMD_STOP = 2002; class UIHandler extends Handler{ public UIHandler() { } @Override public void handleMessage(Message msg) { // Todo Auto-generated method stub Log.d("MyHandler","handleMessage......"); super.handleMessage(msg); Bundle b = msg.getData(); int vCmd = b.getInt("cmd"); switch(vCmd) { case CMD_RECORDING_TIME: int vTime = b.getInt("msg"); MainActivity.this.txt.setText("正在录音中,已录制:"+vTime+" s"); break; case CMD_RECORDFAIL: int vErrorCode = b.getInt("msg"); String vMsg = ErrorCode.getErrorInfo(MainActivity.this,vErrorCode); MainActivity.this.txt.setText("录音失败:"+vMsg); break; case CMD_STOP: int vFileType = b.getInt("msg"); switch(vFileType){ case FLAG_WAV: AudioRecordFunc mRecord_1 = AudioRecordFunc.getInstance(); long mSize = mRecord_1.getRecordFileSize(); MainActivity.this.txt.setText("录音已停止.录音文件:"+AudioFileFunc.getWavFilePath()+"\n文件大小:"+mSize); break; case FLAG_AMR: MediaRecordFunc mRecord_2 = MediaRecordFunc.getInstance(); mSize = mRecord_2.getRecordFileSize(); MainActivity.this.txt.setText("录音已停止.录音文件:"+AudioFileFunc.getAMRFilePath()+"\n文件大小:"+mSize); break; } break; default: break; } } }; class UIThread implements Runnable { int mTimeMill = 0; boolean vRun = true; public void stopThread(){ vRun = false; } public void run() { while(vRun){ try { Thread.sleep(1000); } catch (InterruptedException e) { // Todo Auto-generated catch block e.printstacktrace(); } mTimeMill ++; Log.d("thread","mThread........"+mTimeMill); Message msg = new Message(); Bundle b = new Bundle();// 存放数据 b.putInt("cmd",CMD_RECORDING_TIME); b.putInt("msg",mTimeMill); msg.setData(b); MainActivity.this.uiHandler.sendMessage(msg); // 向Handler发送消息,更新UI } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
angular6 路由拼接查询参数如 ?id=1 并获取url参数
angular6 路由拼接查询参数如 ?id=1 并获取url参数
路由拼接参数:
<div class="category-border" [routerLink]="[‘/list/‘ + category.id + ‘/‘ + category.slug]" [queryParams]="{id: 1}">
拼接后在浏览器显示: 域名 http://localhost:4200/?id=1
angular 获取参数 id 的值:
引用API: import { ActivatedRoute,Params } from ‘@angular/router’;
this.activeRoute.queryParams.subscribe((params: Params) => { this.source = params[‘id‘]; });
今天关于使用 C# 9 的 records 作为强类型 ID - 路由和查询参数和c#强类型和弱类型的介绍到此结束,谢谢您的阅读,有关标签的coords里面的值怎么根据图片大小改变,自动获取?、android-如何使用setMaxDuration限制AudioRecord作为MediaRecorder的录制时间、Android录音--AudioRecord、MediaRecorder的使用、angular6 路由拼接查询参数如 ?id=1 并获取url参数等更多相关知识的信息可以在本站进行查询。
本文标签: