1.AVPlayer简单使用
//url自己随便百度整一个可以播放音乐就行
//注意打开网络协议 不然不能上网
//player是AVPlayer类的对象 必须设置为全局变量
NSString *str =@"http://127.0.0.1/%E7%AC%AC%E4%B8%80%E5%A4%AB%E4%BA%BA.mp3";
NSURL *url = [NSURLURLWithString:str];
player = [[AVPlayeralloc]initWithURL:url];
[playerplay];
//暂停[playerpause];
2.将本地声音转为系统声音 并播放 注意声音文件格式
NSString *path = [[NSBundlemainBundle]pathForResource:@"44th Street Medium.caf"ofType:nil];//这个文件自己拖进工程
NSURL *url =[NSURLfileURLWithPath:path];
//注册为系统声音
UInt32 soundID;
AudioServicesCreateSystemSoundID((__bridgeCFURLRef _Nonnull)(url), &soundID);
AudioServicesPlaySystemSound(soundID);
//震动播放真机尝试才行
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
//将制定的系统声音给销毁
//AudioServicesDisposeSystemSoundID(soundID);
3.录音以及播放
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
{
NSString *recorderPath;
AVAudioRecorder *audioRecoder;
AVAudioPlayer *player;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
UIButton *startRecoderbtn = [UIButtonbuttonWithType:UIButtonTypeCustom];
startRecoderbtn.frame =CGRectMake(100,100, 100,50);
[startRecoderbtn setTitle:@"开始录音"forState:UIControlStateNormal];
startRecoderbtn.backgroundColor = [UIColororangeColor];
[startRecoderbtn addTarget:selfaction:@selector(starRecoder)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:startRecoderbtn];
UIButton *stopRecoderbtn = [UIButtonbuttonWithType:UIButtonTypeCustom];
stopRecoderbtn.frame =CGRectMake(100,200, 100,50);
[stopRecoderbtn setTitle:@"停止录音"forState:UIControlStateNormal];
stopRecoderbtn.backgroundColor = [UIColororangeColor];
[stopRecoderbtn addTarget:selfaction:@selector(stopRecoder)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:stopRecoderbtn];
UIButton *playRecoderbtn = [UIButtonbuttonWithType:UIButtonTypeCustom];
playRecoderbtn.frame =CGRectMake(100,300, 100,50);
[playRecoderbtn addTarget:selfaction:@selector(playRecoder)forControlEvents:UIControlEventTouchUpInside];
[playRecoderbtn setTitle:@"播放录音"forState:UIControlStateNormal];
playRecoderbtn.backgroundColor = [UIColororangeColor];
[self.viewaddSubview:playRecoderbtn];
recorderPath = [NSHomeDirectory()stringByAppendingPathComponent:@"av.caf"];
NSLog(@"%@",NSHomeDirectory());
}
- (void)starRecoder{
NSURL *url = [NSURLfileURLWithPath:recorderPath];
NSMutableDictionary *settring = [NSMutableDictionarydictionary];
//音频格式
settring[AVFormatIDKey] =@(kAudioFormatAppleIMA4);
audioRecoder = [[AVAudioRecorderalloc]initWithURL:urlsettings:settring error:nil];
[audioRecoderprepareToRecord];
[audioRecoderrecord];
}
- (void)stopRecoder{
[audioRecoder pause];
}
- (void)playRecoder{
NSURL *url = [NSURL fileURLWithPath:recorderPath];
player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
[player play];
}