美文网首页
iOS 利用AVAudioPlayer写一个简易的音乐播放器

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

作者: Cary9396 | 来源:发表于2018-07-06 11:21 被阅读0次

利用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

相关文章

网友评论

      本文标题:iOS 利用AVAudioPlayer写一个简易的音乐播放器

      本文链接:https://www.haomeiwen.com/subject/gggeuftx.html