代碼: ViewController.m ...
代碼:
ViewController.m
#import "ViewController.h"
//錄音
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
{
//播放器
AVAudioPlayer *player;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
//點擊任何處的時候,播放聲音
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//https://wifamily.blob.core.chinacloudapi.cn/wom/2015090211559116.mp3
//播放的時候聲音小
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
NSString *voiceUrl=@"https://wifamily.blob.core.chinacloudapi.cn/wom/2015090211559116.mp3";
NSLog(@"---voiceUrl--%@",voiceUrl);
NSURL *url = [[NSURL alloc]initWithString:voiceUrl];
NSData * audioData = [NSData dataWithContentsOfURL:url];
//將數據保存到本地指定位置
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp3", docDirPath , @"temp"];
[audioData writeToFile:filePath atomically:YES];
//播放本地音樂
NSError *playerError;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&playerError];
if (player == nil)
{
NSLog(@"--play--error---%@", [playerError description]);
}else{
[player play];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end