使用AVAudioPlayer播放音乐文件无声音

本文介绍了如何使用AVAudioPlayer播放本地音乐文件的方法,包括声明全局变量、初始化播放器及解决扬声器无声等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用AVAudioPlayer播放本地音乐文件。

1、声明全局AudioPlayer变量:

@property(nonatomic,strong)AVAudioPlayer *movePlayer ; 
 
2、初始化变量并播放:
NSString *tmp=[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"a.mp3"]; 
//NSString * tmp = [[NSBundle mainBundle] pathForResource:@"a" ofType:@"mp3"]; 
NSURL *medioUrl=[NSURL fileURLWithPath:[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"audio/move.mp3"]];  
NSError *err=nil;  
self.movePlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:medioUrl error:&err];  
self.movePlayer.volume=1.0;  
[self.movePlayer prepareToPlay];

if (err!=nil) {  

NSLog(@"move player init error:%@",err);  

}else {  

 [self.movePlayer play]; 

}

3、AVAudioPlayer 模拟器有声音,真机耳机有声音,扬音器没有声音解决办法

在创建:AVAudioPlayer前,加入以下代码

AVAudioSession *audioSession = [AVAudioSession sharedInstance];  

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];  

[audioSession setActive:YES error:nil]; 

 

转载于:https://www.cnblogs.com/huaixu/p/6747268.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值