今天寫了個文字轉語音的方法,其實使用很簡單,文檔資料也很簡單! 主要是一個類目:
.h文件
//
// StrinToVoiceModel.h
// 文字轉語音
//
// Created by 趙小二 on 2018/6/1.
// Copyright © 2018年 趙小二. All rights reserved.
//
/***********************
當前只支持根據中文播放簡體中文,也可以根據英文播放英式英語
後期會慢慢完善各種語言轉換
**********************/
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface StrinToVoiceModel : NSObject
@property(nonatomic,assign)float rate; //語速
@property(nonatomic,assign)float volume; //音量
@property(nonatomic,assign)float pitchMultiplier; //音調
@property(nonatomic,assign)BOOL autoPlay; //是否支持自動播放
/**
實例化對象
@return 返回當前類
*/
+ (StrinToVoiceModel *)playInit;
/**
根據文字播放語音
*/
- (void)playWithString:(NSString *)string;
/**
實例化的時候設置默認屬性
@param vloum 音量
@param rate 語速
@param pichMutiplier 音調
*/
- (void)setDefaultVloume:(float)vloum rate:(CGFloat)rate picchMutiplier:(CGFloat)pichMutiplier;
@end
.m文件
//
// StrinToVoiceModel.m
// 文字轉語音
//
// Created by 趙小二 on 2018/6/1.
// Copyright © 2018年 趙小二. All rights reserved.
//
#import "StrinToVoiceModel.h"
static StrinToVoiceModel *soundPalyer = nil;//設置靜態變量,全局只實例化一次,並且不可更改類目
@implementation StrinToVoiceModel
+ (StrinToVoiceModel *)playInit{
if (soundPalyer == nil) {
soundPalyer = [[StrinToVoiceModel alloc] init];
[soundPalyer setDefaultVloume:-1.0 rate:-1.0 picchMutiplier:-1.0];
}
return soundPalyer;
}
- (void)playWithString:(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];
}
}
/**
* 設置播放的聲音參數 如果選擇默認請傳入 -1.0
*
* @param vloum 音量(0.0~1.0)默認爲1.0
* @param rate 語速(0.0~1.0)
* @param pichMutiplier 語調 (0.5-2.0)
*/
- (void)setDefaultVloume:(float)vloum rate:(CGFloat)rate picchMutiplier:(CGFloat)pichMutiplier{
self.rate = rate;
self.volume = vloum;
self.pitchMultiplier = pichMutiplier;
if (rate == -1.0) {
self.rate = 1;
}
if (vloum == -1.0) {
self.volume = 1;
}
if (pichMutiplier == -1.0) {
self.pitchMultiplier = 1;
}
}
@end
使用方法:
//使用方法舉例 導入頭文件後,用一下方法即可實現
StrinToVoiceModel *palyer = [StrinToVoiceModel playInit];
[palyer setDefaultVloume:-1.0 rate:0.4 picchMutiplier:-1.0];
[palyer playWithString:@"我是趙小二"];