ios开发--音乐的播放

版权声明:资源共享,为我中华IT尽一份绵薄之力,号召无私的黑客奉献精神。。。。。。。。。 https://blog.csdn.net/chaoge321/article/details/50845062

一、简单说明

              音乐播放用到的一个叫做AVAudioPlayer的类,这个类可以用于播放手机本地的音乐文件
注意:
          (1)该类(AVAudioPlayer)只能用于播放本地音频
          (2)时间比较短的(称之为音效)使用AudioServicesCreateSystemSoundID来创建,而本地时间较长的(称之为音乐)使得AVAudioPlayer类。

二、代码示例


           AVAudioPlayer类依赖于AVFoundation框架,因此使用该类必须先导入AVFoundation框架,并包含其头文件(包括主头文件即可)。
           
导入必要的,需要播放的音频文件到项目中。
代码示例:
#import "YYViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface YYViewControllerr ()

@end

@implementation YYViewController
 
- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     //音频文件的url路径
     NSURL *url = [NSBundle mainBundle]URLForResource:@"23513.mp3" withExtension:Nil];
     //创建播放器
     AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
      //缓冲
      [audioPlayer prepareToPlay];
      //播放
      [audioPlayer play];

}
@end
代码说明 :运行程序,点击模拟器界面,却并没有能够播放音频文件,原因是代码中创建的AVAudioPlayer的播放器是一个局部变量,应该调整为全局属性。
可将代码调整如下,即可播放音频



猜你喜欢

转载自blog.csdn.net/chaoge321/article/details/50845062