IOS 播放实现

播放声音可以通过3中方式来完成。

1.AVAudioPlayer

使用简单方便,但只能播放本地音频,不支持流媒体播放。

 //初始化文件地址
NSBundle *bundle = [NSBundle mainBundle];
NSString *filePath = [bundle pathForResource:@"fileName" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:filePath];

//初始化音频对象
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
[player prepareToPlay];
//播放
if([player play])
{
NSLog(@"正在播放");
}

if([player isPlaying])
{
NSLog(@"检测播放状态");
}

//暂停播放
[player pause];

//停止播放
[player stop];

//其他常用属性
//1.音量
player.volume = 0.8;//设置音量(0-1之间)

//2.循环次数
player.numberOfLoops = 3;//默认只播放一次
NSLog(@"总时长 %f",player.duration); //总时长

//3.播放位置
player.currentTime = 15.0;//从指定的位置开始播放
这里可以通过添加代理来监听文件是否播放成功或其他的方法

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

2.AVPlayer

iOS4.0以后,可以使用AVPlayer播放本地音频和支持流媒体播放,但提供接口较少,处理音频不够灵活。

 //可以播放网络资源
NSString *filePath = @"http://www.xxx.1112321.mp3";
NSURL *url = [NSURL URLWithString:filePath];

AVPlayer *player = [[AVPlayer alloc] initWithURL:url];
[player play];

3.播放系统声音

 //1.注册系统声音
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)@"filePathUrl", &soundID);
//filePathUrl文件的类型格式为:caf/wav/aiff格式,且时长小于30s

//2.1播放声音
AudioServicesPlaySystemSound(soundID);

//2.2播放震动
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值