您的位置:首页 > 运维架构

AVAudioPlayer播放本地音频

2016-10-12 14:56 489 查看
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
//记录systemSoundID
@property (nonatomic, assign) SystemSoundID systemID;
//记录播放器对象
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@end

@implementation ViewController

- (AVAudioPlayer *)audioPlayer {
if (!_audioPlayer) {
NSURL *audioFilePath = [[NSBundle mainBundle] URLForResource:@"AllOfMe.mp3" withExtension:nil];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFilePath error:nil];
}
return _audioPlayer;
}

//播放音效(<=30s)
- (IBAction)playShortAudio:(id)sender {
//真机:如果播放系统提供声音(1000 ~ 2000)/震动(静音状态)
AudioServicesPlaySystemSound(1600);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
//播放本地音效文件(创建systemID+播放)
NSString *shortAudioPath = [[NSBundle mainBundle] pathForResource:@"audio.wav" ofType:nil];
NSURL *url = [NSURL fileURLWithPath:shortAudioPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &_systemID);
//播放
AudioServicesPlaySystemSound(_systemID);

}
//播放本地音频文件
- (IBAction)playLocalAudioFile:(id)sender {
if ([self.audioPlayer prepareToPlay]) {
//可以将音频文件文件的数据读到内存(快)
[self.audioPlayer play];
}
}
//暂停
- (IBAction)pauseAudioFile:(id)sender {
if (self.audioPlayer.playing) {
//正在播放
[self.audioPlayer pause];
}
}
//停止(下次播放,从头开始)
- (IBAction)stopAudioFile:(id)sender {
//设置当前播放的时间偏移量offset为0
[self.audioPlayer stop];
self.audioPlayer.currentTime = 0;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: