【代码笔记】iOS-播放从网络上下载的语音_移动开发_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > 移动开发 > 【代码笔记】iOS-播放从网络上下载的语音

【代码笔记】iOS-播放从网络上下载的语音

 2017/8/15 23:31:24  弦外雨  程序员俱乐部  我要评论(0)
  • 摘要:代码:ViewController.m#import"ViewController.h"//录音#import<AVFoundation/AVFoundation.h>@interfaceViewController(){//播放器AVAudioPlayer*player;}@end@implementationViewController-(void)viewDidLoad{[superviewDidLoad]
  • 标签:笔记 iOS 下载 代码 网络

代码:

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

 

发表评论
用户名: 匿名