AVAudioPlayer播放本地音频

51 篇文章 0 订阅
#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值