調(diào)用一句話,播放指定文字

一、說明

最近項目中用到播放文字語音功能,經(jīng)過搜索總結(jié),做了一個簡單封裝,實現(xiàn)調(diào)用一句話播放制定文字功能。
下載地址:GitHub
調(diào)用如下:

[self playNotifySound:@"播放此文字"];

二、

1、demo中包含兩個文件
SDSoundPlayer.h
SDSoundPlayer.m

SDSoundPlayer.h 中首先需要倒入基礎(chǔ)框架

#import <AVFoundation/AVFoundation.h>

然后定義屬性及方法

@property(nonatomic,assign)float rate;   //語速
@property(nonatomic,assign)float volume; //音量
@property(nonatomic,assign)float pitchMultiplier;  //音調(diào)
@property(nonatomic,assign)BOOL  autoPlay;  //自動播放
//實例對象
+(SDSoundPlayer *)SDSoundPlayerInit;
//基礎(chǔ)屬性設(shè)置
-(void)setDefaultWithVolume:(float)aVolume rate:(CGFloat)aRate pitchMultiplier:(CGFloat)aPitchMultiplier;
//播放文字
-(void)play:(NSString *)string;

SDSoundPlayer.m 中實現(xiàn)播放聲音的方法,語速、音量、語言、語調(diào)都可以行修改 ,這里只說一下播放聲音的方法,其他方法請自行下載demo查看 ****zh-CN是中文普通話****

//播放聲音
-(void)play:(NSString *)string{
    if(string && string.length > 0){        
        AVSpeechSynthesizer *player  = [[AVSpeechSynthesizer alloc]init];
        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:string];//語音內(nèi)容
        utterance.voice  = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//語言
        utterance.rate   = self.rate;  //語速
        utterance.volume = self.volume;  //音量(0.0~1.0)默認為1.0
        utterance.pitchMultiplier    = self.pitchMultiplier;  //語調(diào) (0.5-2.0)
        utterance.postUtteranceDelay = 1; 
        [player speakUtterance:utterance];        
    }    
}

三、具體使用

在要使用的地方導入

#import "SDSoundPlayer.h"

寫一個方法,其中message即為要播放的文字

- (void)playNotifySound:(NSString *)message {
    SDSoundPlayer *player = [SDSoundPlayer SDSoundPlayerInit];    
    [player setDefaultWithVolume:-1.0 rate:0.5 pitchMultiplier:-1.0];
    [player play:message];
}

調(diào)用

[self playNotifySound:message];

目前找到的只有這個方法是稍微簡單的,但是聽起來聲音不太好聽

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容