#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>
//如果想使用音乐播放功能 就必须导入AVFoundation
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVAudioPlayerDelegate>
{
AVAudioPlayer *player;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
// AudioToolbox 通过系统声音ID 播放音效
NSString *path = [[NSBundle mainBundle]pathForResource:@"背景音乐.caf" ofType:nil];
// 注册系统声音的ID
SystemSoundID ID = 1;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath:path]), &ID);
// 播放
AudioServicesPlayAlertSound(ID);
// 播放带有震动的
// AudioServicesPlayAlertSound(ID);
*/
[self creatPlayerWithAudioName:@""];
}
- (void)creatPlayerWithAudioName:(NSString *)name
{
// 初始化音乐播放器
NSString *path = [[NSBundle mainBundle]pathForResource:@"背景音乐.caf" ofType:nil];
if (player) {
player = nil;
}
NSError *error;
player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
// 音量
player.volume = 0.3;
// 速率 如果想设置播放速率 必须 得先开启允许设置
player.enableRate = YES;
player.rate = 1;
// 声道(-1.0左声道 0.0中间 1.右声道 )
player.pan = -1.0;
// 循环次数 0播放一次 负数循环播放 正数设置为+1
player.numberOfLoops = -1;
// 预播放 (把音乐文件加载到内存)
[player prepareToPlay];
player.delegate = self;
// 设置音乐播放器 当前的播放时间
player.currentTime = 150;
// duration 总时长 只读
NSLog(@"音乐的总时长%f",player.duration);
NSLog(@"通道的数量%ld",player.numberOfChannels);
[player play];
// player.isPlaying
// 暂停
// [player pause];
// 停止
// [player stop];
NSLog(@"设备当前时间%f",player.deviceCurrentTime);
}
#pragma mark --------代理方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"....");
}
@end

被折叠的 条评论
为什么被折叠?



