iOS 利用AVAudioPlayer写一个简易的音乐播放器

利用AVFoundation库中的AVAudioPlayer类实现简单的音乐播放:

核心代码:

NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"mp3"];

  NSURL *url = [NSURL fileURLWithPath:path];

self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

if([UIApplication sharedApplication].applicationState== UIApplicationStateBackground)  {

NSLog(@"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx后台播放");

[_player play];

UIApplication *app = [UIApplication sharedApplication];

UIBackgroundTaskIdentifier newTask = [app beginBackgroundTaskWithExpirationHandler:nil];

if(bgTask!= UIBackgroundTaskInvalid) {

[app endBackgroundTask: bgTask]; } bgTask = newTask; }

else{

NSLog(@"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx前台播放");

[_player prepareToPlay];

[_player setVolume:1];

_player.numberOfLoops = 1; //设置音乐播放次数 -1为一直循环

[_player play]; //播放 }

具体内容请参看Demo

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容