AVFoundation iOS播放本地音频 语音识别

AVFoundation是一个很强大的系统库,文档介绍如下:

AVFoundation is one of several frameworks that you can use to play and create time-based audiovisual media. It provides an Objective-C interface you use to work on a detailed level with time-based audiovisual data. For example, you can use it to examine, create, edit, or reencode media files. You can also get input streams from devices and manipulate video during realtime capture and playback. Figure I-1 shows the architecture on iOS
AVFoundation是一个可以用来播放和创建基于时间的视听媒体的框架。 它提供了一个Objective-C界面,用于使用基于时间的视听数据的详细级别。 例如,您可以使用它来检查,创建,编辑或重新编码媒体文件。 还可以在设备中实时捕获和播放期间从设备获取输入流并操纵视频。

简单做一个学习笔记。暂时只涉及到一个简单的本地音频播放器和音频识别功能。

本地音频播放器效果如下:


实现功能主要有播放、暂停、停止、循环次数、音量、播放进度展示、播放跳转、音频信息展示。

这些功能基本上都在类 AVAudioPlayer已经封装好了。

简单地在播放功能里面抓取音频路径并播放

       [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        NSURL *url = [NSURL fileURLWithPath:path];
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        _audioPlayer.delegate = self;
        _audioPlayer.meteringEnabled = YES;
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(monitor) userInfo:nil repeats:YES];
        
        [_audioPlayer play];

可初始化一个timer用来实时更新音频播放进度。

相关音量控制,循环次数之类都有现成接口

    _audioPlayer.volume = _audioVol.value;
    _audioPlayer.numberOfLoops = self.cyc.value;

简单地可以在timer的回调中获取一些信息,比如说音频通道数,时长,音频相关信息,并做播放进度跟踪。

   NSUInteger channels = _audioPlayer.numberOfChannels;
    NSTimeInterval duration = _audioPlayer.duration;
    [_audioPlayer updateMeters];
    NSString *audioInfoValue = [[NSString alloc] initWithFormat:@"%f,%f\nchannels=%lu  duration=%lu\n currentTime = %f",[_audioPlayer peakPowerForChannel:0],[_audioPlayer peakPowerForChannel:1], channels, (unsigned long)duration, _audioPlayer.currentTime];
    self.textView.text = audioInfoValue;
    self.audioProgress.progress = _audioPlayer.currentTime / _audioPlayer.duration;

很简单的功能实现,实际使用时做好一些边际判断就好。


语音识别。

用俩个类即可以在不借助第三方的情况下实现语音播放文字内容。

AVSpeechSynthesizer
AVSpeechUtterance

实现如下

    self.speechManager = [[AVSpeechSynthesizer alloc] init];
    _speechManager.delegate = self;
    
    //语音识别
    AVSpeechUtterance *aut = [AVSpeechUtterance speechUtteranceWithString:@"welcom to 四川成都"];
    aut.rate = 0.5; //速度 正常播放
    [_speechManager speakUtterance:aut];

注意播放文字中英文混合的时候,需要设置系统语言为中文即可识别。


***以上  项目名称Tyun_AudioDemo

(欢迎随手给一颗星星哦~)本篇博客Demo地址https://github.com/xmy0010/DemoForCSDN

本人邮箱[email protected]欢迎小伙伴一起讨论,学习,进步。




猜你喜欢

转载自blog.csdn.net/xmy0010/article/details/79482090