@interface ViewController ()<AVAudioPlayerDelegate>
{
AVAudioPlayer *audioPlayer;
}
@end
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(100, 100, 100, 100); button.backgroundColor = [UIColor brownColor]; [button setTitle:@"Play" forState:UIControlStateNormal]; [button setTitle:@"Pause" forState:UIControlStateSelected]; [button addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; [self playMusicWithName:@"TFBOYS-青春修炼手册.mp3"];
- (void)play:(UIButton *)sender{
sender.selected = !sender.selected;
sender.selected != YES ? [audioPlayer pause]:[audioPlayer play];
}
- (void)playMusicWithName:(NSString *)name{
NSError *error;
// 创建一个音乐播放对象
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[[NSBundle mainBundle]URLForResource:name withExtension:nil] error:&error];
if (error) {
NSLog(@"%@",error);
}
预播放
[audioPlayer prepareToPlay];
播放 在这里不写在这 但它是必须的步骤
[audioPlayer play];
获取 当前音乐的声道
NSLog(@"%ld",audioPlayer.numberOfChannels);
durtion:获得播放音频的时间
设置声道 -1.0左 0.0中间 1.0右
audioPlayer.pan = 0.0;
音量
audioPlayer.volume = 0.1;
设置速率 必须设置enableRate为YES
audioPlayer.enableRate = YES;
设置速率 0.5是一半的速度 1.0普通 2.0双倍速率
audioPlayer.rate = 1.0;
currentTime 获得时间
获得峰值 必须设置meteringEnabled为YES
audioPlayer.meteringEnabled = YES;
更新峰值
[audioPlayer updateMeters];
获得当前峰值
NSLog(@"当前峰值:%f",[audioPlayer peakPowerForChannel:2]);
NSLog(@"平均峰值%f",[audioPlayer averagePowerForChannel:2]);
设置播放次数 负数是无限循环的 0 是一次 1是两次 依次类推
audioPlayer.numberOfLoops = 0;
挂上代理
audioPlayer.delegate = self;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有