要求语音转文字 从网上找到一些代码 自己改了一下留存 目前能满足我的要求 其他跟着改进
首先加入框架XCode8以上,只有它之后的编译器里才有Speech.framework
在info.plist文件中添加
Privacy - Speech Recognition Usage Description使用语音识别的
Privacy - Microphone Usage Description使用麦克风的
在需要的VC里
#import <Speech/Speech.h>
SFSpeechRecognizerDelegate代理
@property(nonatomic,strong)SFSpeechAudioBufferRecognitionRequest * recognitionRequest ;//语音请求对象
@property(nonatomic,strong)SFSpeechRecognitionTask * recognitionTask ;//当前语音识别进程
@property(nonatomic,strong)AVAudioEngine * audioEngine ;//声音处理器
@property(nonatomic,strong)SFSpeechRecognizer * recognizer ;//语音识别器
@property (nonatomic, strong) UIButton *startBtn; // 启动按钮
我这里的是用textView 接收文字
UITextView *ownTextView;// 自我介绍
UILabel *ownLabel;//textView 为空 这显示
UILabel *numLabel;// 字数限制
在
viewDidLoad里
//将设备识别语音为中文
NSLocale *cale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh-CN"];
self.recognizer = [[SFSpeechRecognizer alloc]initWithLocale:cale];
_startBtn.enabled = false;
//设置代理
self.recognizer.delegate = self;
self.audioEngine = [[AVAudioEngine alloc]init];
在按钮方法里
- (void)BtnClick:(UIButton *)sender {
//语音识别
[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
bool isButtonEnabled = false;
switch (status) {
case SFSpeechRecognizerAuthorizationStatusAuthorized:
isButtonEnabled = true;
NSLog(@"可以语音识别");
break;
case SFSpeechRecognizerAuthorizationStatusRestricted:
isButtonEnabled = false;
NSLog(@"不能在该设备上进行语音识别");
break;
case SFSpeechRecognizerAuthorizationStatusNotDetermined:
isButtonEnabled = false;
NSLog(@"没有授权语音识别");
break;
case SFSpeechRecognizerAuthorizationStatusDenied:
isButtonEnabled = false;
NSLog(@"用户被拒绝访问语音识别");
UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"打开麦克风和语音识别才能录音" message:@"请在设置中打开麦克和语音识别" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * ok =[UIAlertAction actionWithTitle:@"去设置中" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
/*打开设置*/
NSURL * settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication]openURL:settingsURL];
}];
UIAlertAction * cacel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alert1 addAction:ok];
[alert1 addAction:cacel];
[self presentViewController:alert1 animated:YES completion:nil];
break;
// break;
}
_startBtn.enabled = isButtonEnabled;
}];
if ([self.audioEngine isRunning]) {
numLabel.text = [NSString stringWithFormat:@"%lu/200字",(unsigned long)ownTextView.text.length];
if (ownTextView.text.length == 0) {
ownLabel.hidden = NO;
}
[self.audioEngine stop];
[self.recognitionRequest endAudio];
_startBtn.enabled = YES;
[_startBtn setTitle:@"开始录制" forState:UIControlStateNormal];
}else{
ownLabel.hidden = YES;
[self startRecording];
[_startBtn setTitle:@"停止录制" forState:UIControlStateNormal];
}
}
- (void)startRecording{
if (self.recognitionTask) {
[self.recognitionTask cancel];
self.recognitionTask = nil;
}
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
bool audioBool = [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
bool audioBool1= [audioSession setMode:AVAudioSessionModeMeasurement error:nil];
bool audioBool2= [audioSession setActive:true withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
if (audioBool || audioBool1|| audioBool2) {
NSLog(@"可以使用");
}else{
NSLog(@"这里说明有的功能不支持");
}
self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc]init];
AVAudioInputNode *inputNode = self.audioEngine.inputNode;
self.recognitionRequest.shouldReportPartialResults = true;
//开始识别任务
self.recognitionTask = [self.recognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
bool isFinal = false;
if (result) {
ownTextView.text = [[result bestTranscription] formattedString]; //语音转文本
numLabel.text = [NSString stringWithFormat:@"%lu/200字",(unsigned long)ownTextView.text.length];
if (ownTextView.text.length >=200) {
ownTextView.text = [ownTextView.text substringToIndex:200];
numLabel.text = @"200/200字";
[[SMProgressHUD shareInstancetype]showErrorTip:@"最对输入200字"];
}
isFinal = [result isFinal];
}
if (error || isFinal) {
[self.audioEngine stop];
[inputNode removeTapOnBus:0];
self.recognitionRequest = nil;
self.recognitionTask = nil;
_startBtn.enabled = true;
}
}];
AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
[inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
[self.recognitionRequest appendAudioPCMBuffer:buffer];
}];
[self.audioEngine prepare];
bool audioEngineBool = [self.audioEngine startAndReturnError:nil];
NSLog(@"%d",audioEngineBool);
ownTextView.text = @"";
numLabel.text = [NSString stringWithFormat:@"%lu/200字",(unsigned long)ownTextView.text.length];
}
到这里 就完成了 语音转文字 布局自己合适写
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通