- (void)playsoundAction:(NSString *)soundWord {
// 播放声音
if (self.textField.text.length > 0) {
soundWord = self.textField.text;
} else {
[KAlertViewFactory showToastWithMessage:@"无法读取该单词"];
return;
}
// 如果是其他字符串,可以先编码,之后在拼接完成,最后使用
// NSString *newUrlString = [contentStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
// NSString * soundAddress = [NSString stringWithFormat:@"https://fanyi.baidu.com/gettts?lan=zh&text=%@&spd=5&source=web",newUrlString];
// [[WL_Tool getInstance] SoundPlayer:soundAddress];
NSString *soundUrl = [NSString stringWithFormat:@"https://fanyi.baidu.com/gettts?lan=zh&text=%@&spd=3&source=wise", soundWord];
// 需要编码:转换成网址格式,以免不是正常网址,造成错误
NSString *urlStr = [soundUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
[[WL_Tool getInstance] SoundPlayer:urlStr];
}
- 调用的方法:拿到音频(这里获取的是.mp3格式的音频,直接播放,退出页面时,停止播放)
//声音播放
-(void)SoundPlayer:(NSString *)strUrl;
{
[[WL_AFShareManager sharedManagerReturnData] GET:strUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//请求成功返回数据 根据responseSerializer 返回不同的数据格式
NSLog(@"%@",task.currentRequest.URL);
[SVProgressHUD dismiss];
self.player=[[AVAudioPlayer alloc]initWithData:responseObject error:nil];
if ([self.player prepareToPlay] &&[self.player play])
{
//成功播放音乐
}
//设置锁屏仍能继续播放
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//请求失败
NSLog(@"%@",task.currentRequest.URL);
NSLog(@"error-->%@",error);
[SVProgressHUD dismiss];
}];
}
// 声音停止播放
- (void)SoundStop {
[self.player stop];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (self.toolBlock !=nil) {
self.toolBlock(0);
}
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error
{
NSLog(@"%@",error.mj_JSONString);
}