您的位置:首页 > 移动开发 > IOS开发

iOS开发——高级篇——音频、音乐播放(封装类)

2015-10-10 09:52 357 查看

一、简介

简单来说,音频可以分为2种
音效
又称“短音频”,通常在程序中的播放时长为1~2秒
在应用程序中起到点缀效果,提升整体用户体验

音乐
比如游戏中的“背景音乐”,一般播放时间较长

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

二、音效

1、音效的播放

// 1.获得音效文件的路径
NSURL *url = [[NSBundle mainBundle] URLForResource:@"m_03.wav" withExtension:nil];

// 2.加载音效文件,得到对应的音效ID
SystemSoundID soundID = 0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);

// 3.播放音效
// 播放音效的同时有震动效果
AudioServicesPlayAlertSound(soundID);
// 仅仅是播放音效
// AudioServicesPlaySystemSound(soundID);

音效文件只需要加载1次

2、音效播放常见函数总结
加载音效文件

AudioServicesCreateSystemSoundID(CFURLRef inFileURL, SystemSoundID *outSystemSoundID)

释放音效资源
AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)

播放音效
AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)

播放音效带点震动
AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)

三、音乐

1、音乐的播放
音乐播放用到一个叫做AVAudioPlayer的类

AVAudioPlayer常用方法
加载音乐文件
- (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;
- (id)initWithData:(NSData *)data error:(NSError **)outError;

准备播放(缓冲,提高播放的流畅性)
- (BOOL)prepareToPlay;

播放(异步播放)
- (BOOL)play;

暂停
- (void)pause;

停止
- (void)stop;

是否正在播放
@property(readonly, getter=isPlaying) BOOL playing;

时长
@property(readonly) NSTimeInterval duration;

当前的播放位置
@property NSTimeInterval currentTime;

播放次数(-1代表无限循环播放,其他代表播放numberOfLoops+1次)
@property NSInteger numberOfLoops;

音量
@property float volume;

是否允许更改速率
@property BOOL enableRate;

播放速率(1是正常速率,0.5是一般速率,2是双倍速率)
@property float rate;

有多少个声道
@property(readonly) NSUInteger numberOfChannels;

声道(-1是左声道,1是右声道,0是中间)
@property float pan;

是否允许测量音量
@property(getter=isMeteringEnabled) BOOL meteringEnabled;

更新测量值
- (void)updateMeters;

获得当前的平均音量
- (float)averagePowerForChannel:(NSUInteger)channelNumber;

四、录音

/** 录音对象 */
@property (nonatomic, strong) AVAudioRecorder *recorder;

#pragma mark - 录制的控制
- (IBAction)startRecorder {
[self.recorder record];
}

- (IBAction)stopRecorder {
[self.recorder stop];
}

#pragma mark - 懒加载代码
- (AVAudioRecorder *)recorder
{
if (_recorder == nil) {
// 1.获取音频存放的路径
// 1.1.URL决定的录制的音频的存放的位置
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

// 1.2.拼接一个音频的文件名称
NSString *filePath = [path stringByAppendingPathComponent:@"123.caf"];

// 1.3.将路径转成URL
NSURL *url = [NSURL fileURLWithPath:filePath];

// 2.设置音频的相关格式:settings : 决定音频的格式/采样率
NSDictionary *setttings = @{
AVFormatIDKey : @(kAudioFormatLinearPCM),
AVSampleRateKey : @(8000)};

// 3.创建录音对象
self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:setttings error:nil];
}
return _recorder;
}


五、播放音乐(抽取工具类)

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>

@interface CHGAudioTool : NSObject

/**
*  根据音效文件名开始播放音效
*
*  @param soundName 音效名称
*/
+ (void)playSoundWithSoundName:(NSString *)soundName;

/**
*  根据音乐文件名开始播放音乐 返回播放器
*
*  @param musicName 音乐名称
*/
+ (AVAudioPlayer *)playMusicWithMusicName:(NSString *)musicName;

/**
*  根据音乐文件名暂停播放音乐
*
*  @param musicName 音乐名称
*/
+ (void)pauseMusicWithMusicName:(NSString *)musicName;

/**
*  根据音乐文件名停止播放音乐
*
*  @param musicName 音乐名称
*/
+ (void)stopMusicWithMusicName:(NSString *)musicName;

@end


实现

#import "CHGAudioTool.h"

@implementation CHGAudioTool

static NSMutableDictionary *_soundIDs;
static NSMutableDictionary *_players;

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

//  播放音频
+ (void)playSoundWithSoundName:(NSString *)soundName
{
// 1.从字典中取出之前保存的soundID
SystemSoundID soundID = [[_soundIDs objectForKey:soundName] unsignedIntValue];

// 2.如果取出为0,表示之前没有加载当前声音
if (soundID == 0) {
// 2.1.根据资源文件加载soundID
CFURLRef url = (__bridge CFURLRef)[[NSBundle mainBundle] URLForResource:soundName withExtension:nil];
AudioServicesCreateSystemSoundID(url, &soundID);

// 2.2.存入字典
[_soundIDs setObject:@(soundID) forKey:soundName];
}

// 3.播放声音
AudioServicesPlaySystemSound(soundID);
}

// 开始播放音乐
+ (AVAudioPlayer *)playMusicWithMusicName:(NSString *)musicName
{
// 1.从字典中取出之前保存的播放器
AVAudioPlayer *player = _players[musicName];

// 2.判断播放器是否为nil,如果为空,则创建播放器
if (player == nil) {
// 2.1.加载对应的资源
NSURL *url = [[NSBundle mainBundle] URLForResource:musicName withExtension:nil];

// 2.2.创建播放器
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

// 2.3.将播放器存入字典
[_players setObject:player forKey:musicName];
}

// 3.播放音乐
[player play];

return player;
}

// 暂停播放音乐
+ (void)pauseMusicWithMusicName:(NSString *)musicName
{
// 1.从字典中取出之前保存的播放器
AVAudioPlayer *player = _players[musicName];

// 2.判断播放器是否为空,如果不为空,则暂停
if (player) {
[player pause];
}
}

// 停止播放音乐
+ (void)stopMusicWithMusicName:(NSString *)musicName
{
// 1.从字典中取出之前保存的播放器
AVAudioPlayer *player = _players[musicName];

// 2.判断播放器是否为空,如果不为空,则停止音乐
if (player) {
[player stop];
[_players removeObjectForKey:musicName];
}
}

@end


抽取出这个工具类后,用法很简单

#import "CHGAudioTool.h"
// 开始播放
[CHGAudioTool playMusicWithMusicName:playingMusic.filename];
// 暂停播放
[CHGAudioTool pauseMusicWithMusicName:playingMusic.filename];
// 停止播放
[CHGAudioTool stopMusicWithMusicName:playingMusic.filename];


playingMusic.filename是你要操作的文件(比如: 小苹果.mp3)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: