調用一句話,播放指定文字

一、說明

最近項目中用到播放文字語音功能,經過搜索總結,做了一個簡單封裝,實現調用一句話播放制定文字功能。
下載地址:GitHub
調用如下:

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

二、

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

SDSoundPlayer.h 中首先需要倒入基礎框架

#import <AVFoundation/AVFoundation.h>

然后定義屬性及方法

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

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

//播放聲音
-(void)play:(NSString *)string{
    if(string && string.length > 0){        
        AVSpeechSynthesizer *player  = [[AVSpeechSynthesizer alloc]init];
        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:string];//語音內容
        utterance.voice  = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//語言
        utterance.rate   = self.rate;  //語速
        utterance.volume = self.volume;  //音量(0.0~1.0)默認為1.0
        utterance.pitchMultiplier    = self.pitchMultiplier;  //語調 (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];
}

調用

[self playNotifySound:message];

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

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容