需要添加链接库 AVFoundation.framework, AudioToolbox.framework
添加头文件
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>
设置路径
#define MUSICSAVE(MUSICNAME) [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Music"]stringByAppendingPathComponent:MUSICNAME]
路径有两种,第一种是使用工程文件
NSString *musicName = [[NSBundlemainBundle] pathForResource:@"孙燕姿-渴" ofType:@"mp3"]
第二种在沙盒目录NSString *musicName = [dic[@"soundUrl"] substringFromIndex:searchRange.location +1];
soundUrl = [NSURL URLWithString:MUSICSAVE(stringName)];
切记,不可以直接使用soundUrl = [NSURL URLWithString:MUSICSAVE([dic[@"soundUrl"] substringFromIndex:searchRange.location + 1];)]; 需要先转成NSString格式,再转成NSURL格式才可以播放
播放音频
player = [[AVAudioPlayeralloc]initWithContentsOfURL:soundUrlerror:nil];
[playerprepareToPlay];
[player play];