今天有個(gè)這個(gè)需求,這東西很簡(jiǎn)單,網(wǎng)上一搜一大片只是記錄一下!上代碼
//
// PPSoundPlayer.h
//
// Created by pipixia on 2017/9/13.
// Copyright ? 2017年 pipixia. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface PPSoundPlayer : NSObject
{
///聲音設(shè)置
NSMutableDictionary *soundSet;
///配置文件路徑
NSString *path;
}
///語(yǔ)速
@property (nonatomic, assign) float rate;
///音量
@property (nonatomic, assign) float volume;
///音調(diào)
@property (nonatomic, assign) float pitchMultiplier;
///自動(dòng)播放
@property (nonatomic, assign) BOOL autoPlay;
+ (PPSoundPlayer *)soundPlayerInstance;
- (void)play:(NSString *)text;
- (void)writeSoundSet;
- (void)stopSpeaking;
@end
//
// PPSoundPlayer.m
//
// Created by pipixia on 2017/9/13.
// Copyright ? 2017年 pipixia. All rights reserved.
//
#import "PPSoundPlayer.h"
static PPSoundPlayer *soundPlayer = nil;
static AVSpeechSynthesizer *player = nil;
static dispatch_queue_t queue = NULL;
@implementation PPSoundPlayer
+ (PPSoundPlayer *)soundPlayerInstance
{
if (soundPlayer == nil)
{
soundPlayer = [[PPSoundPlayer alloc] init];
player = [[AVSpeechSynthesizer alloc] init];
queue = dispatch_queue_create("text", NULL);
[soundPlayer initSoundSet];
[soundPlayer setDefault];
}
return soundPlayer;
}
//播放聲音
- (void)play:(NSString *)text
{
if(text)
{
dispatch_async(queue, ^{
AVSpeechUtterance *u=[[AVSpeechUtterance alloc]initWithString:text];//設(shè)置要朗讀的字符串
u.voice=[AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//設(shè)置語(yǔ)言
u.volume = self.volume; //設(shè)置音量(0.0~1.0)默認(rèn)為1.0
u.rate = self.rate; //設(shè)置語(yǔ)速
u.pitchMultiplier = self.pitchMultiplier; //設(shè)置語(yǔ)調(diào)
[player speakUtterance:u];
});
}
}
//初始化配置
- (void)initSoundSet
{
path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"SoundSet.plist"];
soundSet=[NSMutableDictionary dictionaryWithContentsOfFile:path];
if(soundSet==nil)
{
soundSet=[NSMutableDictionary dictionary];
[soundPlayer setDefault];
[soundPlayer writeSoundSet];
}
else
{
self.autoPlay = [[soundSet valueForKeyPath:@"autoPlay"] boolValue];
self.volume = [[soundSet valueForKeyPath:@"volume"] floatValue];
self.rate = [[soundSet valueForKeyPath:@"rate"] floatValue];
self.pitchMultiplier = [[soundSet valueForKeyPath:@"pitchMultiplier"] floatValue];
}
}
//恢復(fù)默認(rèn)設(shè)置
- (void)setDefault
{
self.volume = 0.7;
self.rate = 0.5;
self.pitchMultiplier = 1.0;
}
//將設(shè)置寫(xiě)入配置文件
-(void)writeSoundSet
{
[soundSet setValue:[NSNumber numberWithBool:self.autoPlay] forKey:@"autoPlay"];
[soundSet setValue:[NSNumber numberWithFloat:self.volume] forKey:@"volume"];
[soundSet setValue:[NSNumber numberWithFloat:self.rate] forKey:@"rate"];
[soundSet setValue:[NSNumber numberWithFloat:self.pitchMultiplier] forKey:@"pitchMultiplier"];
[soundSet writeToFile:path atomically:YES];
}
- (void)stopSpeaking{
[player stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
@end