最近一个工程中,需要对高、低电压进行报警,其实很简单,只需把声音文件导入工程,直接播放即可。代码解析如下:
1.导入框架<AVFoundation/AVFoundation.h>,添加代理AVAudioPlayerDelegate;
2.获取本地声音文件路径path,并生成NSURL对象;
3.初始化一个音频对象musicPlayer,设置相关属性;
4.调用play方法播放音频。
#import <AVFoundation/AVFoundation.h>
@interface XXX ()<AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *musicPlayer;
- (void)playNotifySound {
//获取路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"jingbao" ofType:@"mp3"];
NSURL *fileUrl = [NSURL URLWithString: path];
if (!self.musicPlayer)
{
self.musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
self.musicPlayer.delegate = self;
}
if (![self.musicPlayer isPlaying])
{
//设置音量
[self.musicPlayer setVolume:0.6];
[self.musicPlayer prepareToPlay];
[self.musicPlayer play];
}
}
网友评论