IOS后台播放音乐

http://www.apple.com.cn/developer/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AudioandVideoTechnologies/AudioandVideoTechnologies.html#//apple_ref/doc/uid/TP40007072-CH19-SW32

 

 

1.首先在工程中导入播放音乐所使用的框架:AV Foundation框架

2.在项目中添加代码:

   导入框架头文件:

#import <AVFoundation/AVFoundation.h>

 

 

   定义播放器变量:

AVAudioPlayer *player;
@property (strong, nonatomic) AVAudioPlayer *player;

 

 

    自定义播放方法:

-(void)playSound{
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    
    NSString *soundFilePath =
    [[NSBundle mainBundle] pathForResource: @"sound" ofType: @"mp3"];
    
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
    [fileURL release];
    
    [player play];
    [player setDelegate: self];
}

 

 

按Home键暂停播放(AppDelegate.m):

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if (self.player.playing) {
        [self.player pause];
    }
}

 

 

 运行软件继续播放(AppDelegate.m):

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    if(self.player.playing == NO){
        [self.player play];
    }
}
模拟器可以测试!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值