iOS开发之 AVAudioPlayer音频播放

1、相关知识点

播放音频可以使用框架
AVFoundation.framework

音效的播放

//1.获得音效文件的路径

NSURL*url= [[NSBundlemainBundleURLForResource:@"m_03.wav"withExtension:nil];

//2.加载音效文件,得到对应的音效ID

SystemSoundIDsoundID=0;

AudioServicesCreateSystemSoundID((__bridgeCFURLRef)(url),&soundID);

//3.播放音效

AudioServicesPlaySystemSound(soundID);

音效文件只需要加载1

音效播放常见函数总结

加载音效文件

AudioServicesCreateSystemSoundID(CFURLRefinFileURL,SystemSoundID*outSystemSoundID)

释放音效资源

AudioServicesDisposeSystemSoundID(SystemSoundIDinSystemSoundID)


播放音效

AudioServicesPlaySystemSound(SystemSoundIDinSystemSoundID)

播放音效带点震动

AudioServicesPlayAlertSound(SystemSoundIDinSystemSoundID)

音效格式








2.示例

//
//  ViewController.m

#import "ViewController.h"
#import "AudioTool.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

/** 播放器 */
@property (nonatomic, strong) AVAudioPlayer *player;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)otherMusic {
    
    [AudioTool playMusicWithMusicName:@"120125029.mp3"];
    
    /*
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"120125029.mp3" withExtension:nil];
    [self.player setValue:url forKeyPath:@"url"];
    
    [self.player play];
     */
}

- (IBAction)play {
    /*
    // 取出资源的URL
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"1201111234.mp3" withExtension:nil];
    
    // 创建播放器
    NSError *error = nil;
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    
    // 准备播放
    [player prepareToPlay];
     */
    
    // 播放歌曲
    // [self.player play];
    [AudioTool playMusicWithMusicName:@"1201111234.mp3"];
}

- (IBAction)pause {
    // [self.player pause];
    [AudioTool pauseMusicWithMusicName:@"1201111234.mp3"];
}

- (IBAction)stop {
    // [self.player stop];
    // self.player = nil;
    [AudioTool stopMusicWithMusicName:@"1201111234.mp3"];
}

//#pragma mark - 懒加载
//- (AVAudioPlayer *)player
//{
//    if (_player == nil) {
//        // 取出资源的URL
//        NSURL *url = [[NSBundle mainBundle] URLForResource:@"1201111234.mp3" withExtension:nil];
//        
//        // 创建播放器
//        NSError *error = nil;
//        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
//        
//        // 准备播放
//        [self.player prepareToPlay];
//    }
//    
//    return _player;
//}

@end

//
//  XMGAudioTool.m
//

#import "AudioTool.h"
#import <AVFoundation/AVFoundation.h>

@implementation AudioTool

static NSMutableDictionary *_soundIDs;
static NSMutableDictionary *_players;

+ (void)initialize
{
    _soundIDs = [NSMutableDictionary dictionary];
    _players = [NSMutableDictionary dictionary];
}

+ (void)playMusicWithMusicName:(NSString *)musicName
{
    assert(musicName);
    
    // 1.定义播放器
    AVAudioPlayer *player = nil;
    
    // 2.从字典中取player,如果取出出来是空,则对应创建对应的播放器
    player = _players[musicName];
    if (player == nil) {
        // 2.1.获取对应音乐资源
        NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:musicName withExtension:nil];
        
        if (fileUrl == nil) return;
        
        // 2.2.创建对应的播放器
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
        
        // 2.3.将player存入字典中
        [_players setObject:player forKey:musicName];
        
        // 2.4.准备播放
        [player prepareToPlay];
    }
    
    // 3.播放音乐
    [player play];
}

+ (void)pauseMusicWithMusicName:(NSString *)musicName
{
    assert(musicName);
    
    // 1.取出对应的播放
    AVAudioPlayer *player = _players[musicName];
    
    // 2.判断player是否nil
    if (player) {
        [player pause];
    }
}

+ (void)stopMusicWithMusicName:(NSString *)musicName
{
    assert(musicName);
    
    // 1.取出对应的播放
    AVAudioPlayer *player = _players[musicName];
    
    // 2.判断player是否nil
    if (player) {
        [player stop];
        [_players removeObjectForKey:musicName];
        player = nil;
    }
}

#pragma mark - 音效的播放
+ (void)playSoundWithSoundname:(NSString *)soundname
{
    // 1.定义SystemSoundID
    SystemSoundID soundID = 0;
    
    // 2.从字典中取出对应soundID,如果取出是nil,表示之前没有存放在字典
    soundID = [_soundIDs[soundname] unsignedIntValue];
    if (soundID == 0) {
        CFURLRef url = (__bridge CFURLRef)[[NSBundle mainBundle] URLForResource:soundname withExtension:nil];
        
        if (url == NULL) return;
        
        AudioServicesCreateSystemSoundID(url, &soundID);
        
        // 将soundID存入字典
        [_soundIDs setObject:@(soundID) forKey:soundname];
    }
    
    // 3.播放音效
    AudioServicesPlaySystemSound(soundID);
}

@end




发布了269 篇原创文章 · 获赞 58 · 访问量 59万+
展开阅读全文

AVAudioPlayer无法播放音频的问题

04-23

今天开始做录音的功能。点击recordbtn开始录音,再次点击,则停止录音,点击play键播放录音 然后就遇到问题了。 点击play键后,[self.audioPlayer prepareToPlay] 总是为no,即使把这个去掉,强制[self.audioPlayer play];也没有效果,请问是怎么回事? 另:用player播放其他音频是可以的,作为对比测试,播放了一首歌曲,没问题,就是播放自己录制的音频出问题,是不是录制的时候就出错了? 附代码: ``` -(void)record{ NSLog(@"recording"); AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryRecord error:nil]; [audioSession setActive:YES error:nil]; NSString *tripReportAudioPath = [self audioRecordingPath]; NSError *err = nil; NSURL *tripReportAudioURL = [NSURL URLWithString:tripReportAudioPath]; AVAudioRecorder *tripReportRecorder = [[AVAudioRecorder alloc]initWithURL:tripReportAudioURL settings:[self audioRecordingSetting] error:&err]; if (tripReportRecorder != nil) { tripReportRecorder.delegate = self; if ([tripReportRecorder prepareToRecord] && self.recordBtn.selected == NO) { self.recordBtn.selected = YES; [tripReportRecorder record]; }else if (self.recordBtn.selected == YES){ self.recordBtn.selected = NO; [tripReportRecorder stop ]; } }else{ NSLog(@"record err:%@",[err description]); } } //生成录音文件地址 -(NSString *)audioRecordingPath{ NSString *result = nil; NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docdir = [folders objectAtIndex:0]; result = [docdir stringByAppendingPathComponent:@"tripReport.caf"]; return result; } //录音器的相关设置 -(NSDictionary *)audioRecordingSetting{ NSDictionary *result = nil; NSMutableDictionary *settings = [[NSMutableDictionary alloc]init ]; //录制的音频格式 [settings setValue:[NSNumber numberWithInteger:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey]; //采样率 [settings setValue:[NSNumber numberWithFloat:44100.0f] forKey:AVSampleRateKey]; //信道数 [settings setValue:[NSNumber numberWithInteger:1] forKey:AVNumberOfChannelsKey]; //录音的质量 [settings setValue:[NSNumber numberWithInteger:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey]; [settings setValue:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey]; [settings setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; result = [NSDictionary dictionaryWithDictionary:settings]; return result; } -(void)play{ AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil]; [audioSession setActive:YES error:nil]; NSError *playBackError = nil; NSError *readingError = nil; NSString *audioPath = [self audioRecordingPath]; // NSString *audioPath = [[NSBundle mainBundle]pathForResource:@"Love" ofType:@"mp3"]; NSLog(@"path:%@",audioPath); NSURL *url = [NSURL URLWithString:audioPath]; NSData *fileData = [NSData dataWithContentsOfFile:audioPath options:NSDataReadingMapped error:&readingError]; self.audioPlayer = [[AVAudioPlayer alloc]initWithData:fileData error:&playBackError]; if (self.audioPlayer != nil) { NSLog(@"finishi3"); self.audioPlayer.delegate = self; self.audioPlayer.volume = 50.0; if ([self.audioPlayer prepareToPlay]) { NSLog(@"finishi4"); UInt32 doChangeDefaultRoute = 1; AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute); [self.audioPlayer play]; } }else{ NSLog(@"error:%@",[playBackError description]); } } ``` 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览