iOS-音频播放

1 iOS的播放音频方式:

1 AVAudioPlayer(只支持本地音乐播放)
2 AVPlayer (既支持本地音乐播放,又支持流媒体音乐播放)
3 系统声音(小的音乐)
4 音频队列
代码实现:

#import "ViewController.h"
#import 

@interface ViewController (){
    AVAudioPlayer *audioPlayer;
    AVPlayer *palyer;
    SystemSoundID soundID;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //1 AVAudioPlayer只能播放本地音乐,不支持流媒体音乐
//    [self audioPlayer];
//    2 AVPlayer既能播放本地音乐,又支持流媒体音乐
//    [self player];
    //3 系统音频
    [self systemAudio];
}

- (void) systemAudio {
    
    //本地url
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"44th Street Medium" ofType:@"caf"];;
    //将该路径转成url格式
    NSURL *url = [NSURL fileURLWithPath:filePath];
    
    /*
     CFURLRef: Core Foundation
     __bridge:桥接  Foundation  <---> Core Foundation
     解决两个框架中对象转换时 内存管理的问题
     //桥接:让ARC管理内存
     
     //手动管理内存:
     CFRelease(fileUrl)
     CFRetain(<#CFTypeRef cf#>)
     
     
     */
    //(1) 注册系统声音(c函数调用)
    //soundID:标示音频
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
    //(2)播放
    AudioServicesPlaySystemSound(soundID);
}

- (void)dealloc
{
    //销毁注册的系统声音(不再使用)
    AudioServicesDisposeSystemSoundID(soundID);
}

- (void) audioPlayer{
    //获取文件名
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"4" ofType:@"mp3"];
    //文件名转换成url格式
    NSURL *url = [NSURL fileURLWithPath:filePath];
    //记得AVAudioPlayer对象设置成全局变量才可以播放
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    audioPlayer.delegate = self;
    [audioPlayer prepareToPlay];
    [audioPlayer play];
}

- (void) player {
    
    //本地音乐播放
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"4" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    //网络音乐播放
    //    NSString *urlStr = @"http://mp3.qqmusic.cc/yq/101803847.mp3";
    //    NSURL *url = [NSURL URLWithString:urlStr];
    
    palyer = [[AVPlayer alloc] initWithURL:url];
    
    
    [palyer play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    
    NSLog(@"播放完成");
}
@end

你可能感兴趣的:(iOS-音频播放)