需要添加鏈接庫 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];