您的位置:首页 > 移动开发 > IOS开发

iOS开发-播放本地音频(可后台播放)

2014-08-23 00:39 351 查看
//初始化音乐
    //创建音乐文件路径
    NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"eyeExe" ofType:@"mp3"];
    
    //判断文件是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:musicFilePath])
    {
        NSURL *musicURL = [NSURL fileURLWithPath:musicFilePath];
        NSError *myError = nil;
        //创建播放器
        myBackMusic = [[***AudioPlayer alloc] initWithContentsOfURL:musicURL error:&myError];
        if (myBackMusic == nil)
        {
            NSLog(@"error === %@",[myError description]);
        }
        [myBackMusic setVolume:1];   //设置音量大小
        myBackMusic.numberOfLoops = -1;//设置音乐播放次数  -1为一直循环
        [myBackMusic prepareToPlay];

    }
    
    //设置锁屏仍能继续播放
    [[***AudioSession sharedInstance] setCategory: ***AudioSessionCategoryPlayback error:nil];
    [[***AudioSession sharedInstance] setActive: YES error: nil];


对应的方法有:
/* methods that return BOOL return YES on success and NO on failure. */
- (BOOL)prepareToPlay;	/* get ready to play the sound. happens automatically on play. */
- (BOOL)play;			/* sound is played asynchronously. */
- (BOOL)playAtTime:(NSTimeInterval)time NS_***AILABLE(10_7, 4_0); /* play a sound some time in the future. time is an absolute time based on and greater than deviceCurrentTime. */
- (void)pause;			/* pauses playback, but remains ready to play. */
- (void)stop;			/* stops playback. no longer ready to play. */

相关参数:
/* properties */

@property(readonly, getter=isPlaying) BOOL playing; /* is it playing or not? */

@property(readonly) NSUInteger numberOfChannels;
@property(readonly) NSTimeInterval duration; /* the duration of the sound. */

/* the delegate will be sent messages from the ***AudioPlayerDelegate protocol */ 
@property(assign) id<***AudioPlayerDelegate> delegate; 

/* one of these properties will be non-nil based on the init... method used */
@property(readonly) NSURL *url; /* returns nil if object was not created with a URL */
@property(readonly) NSData *data; /* returns nil if object was not created with a data object */

@property float pan NS_***AILABLE(10_7, 4_0); /* set panning. -1.0 is left, 0.0 is center, 1.0 is right. */
@property float volume; /* The volume for the sound. The nominal range is from 0.0 to 1.0. */

@property BOOL enableRate NS_***AILABLE(10_8, 5_0); /* You must set enableRate to YES for the rate property to take effect. You must set this before calling prepareToPlay. */
@property float rate NS_***AILABLE(10_8, 5_0); /* See enableRate. The playback rate for the sound. 1.0 is normal, 0.5 is half speed, 2.0 is double speed. */

/*  If the sound is playing, currentTime is the offset into the sound of the current playback position.  
If the sound is not playing, currentTime is the offset into the sound where playing would start. */
@property NSTimeInterval currentTime;

/* returns the current time associated with the output device */
@property(readonly) NSTimeInterval deviceCurrentTime NS_***AILABLE(10_7, 4_0);

/* "numberOfLoops" is the number of times that the sound will return to the beginning upon reaching the end. 
A value of zero means to play the sound just once.
A value of one will result in playing the sound twice, and so on..
Any negative number will loop indefinitely until stopped.
*/
@property NSInteger numberOfLoops;

/* settings */
@property(readonly) NSDictionary *settings NS_***AILABLE(10_7, 4_0); /* returns a settings dictionary with keys as described in ***AudioSettings.h */

/* metering */

@property(getter=isMeteringEnabled) BOOL meteringEnabled; /* turns level metering on or off. default is off. */

- (void)updateMeters; /* call to refresh meter values */

- (float)peakPowerForChannel:(NSUInteger)channelNumber; /* returns peak power in decibels for a given channel */
- (float)averagePowerForChannel:(NSUInteger)channelNumber; /* returns average power in decibels for a given channel */


后台播放音频方法:
1. plist文件中添加一行 Required background modes
添加一个items,设置属性为:App plays audio or streams audio/video using AirPlay
如下所示:



2.添加如下代码:
//设置锁屏仍能继续播放
    [[***AudioSession sharedInstance] setCategory: ***AudioSessionCategoryPlayback error:nil];
    [[***AudioSession sharedInstance] setActive: YES error: nil];


设置了***AudioSessionCategoryPlayback,表示对于用户切换静音模式或者锁屏 都不理睬,继续播放音乐。并且不播放来自其他app的音乐,当然你可以设置kAudioSessionProperty_OverrideCategoryMixWithOthers 来实现与其他app的音乐混合。
除***AudioSessionCategoryPlayback外,还有以下其他category

NSString *const ***AudioSessionCategoryAmbient;    
NSString *const ***AudioSessionCategorySoloAmbient;    
NSString *const ***AudioSessionCategoryPlayback;    
NSString *const ***AudioSessionCategoryRecord;    
NSString *const ***AudioSessionCategoryPlayAndRecord;    
NSString *const ***AudioSessionCategoryAudioProcessing;

***AudioSessionCategoryAmbient 静音模式或者锁屏下不再播放音乐,和其他app声音混合。
***AudioSessionCategorySoloAmbient 默认模式,静音模式或者锁屏下不再播放音乐,不和其他app声音混合。
***AudioSessionCategoryRecord 不播放音乐,锁屏状态继续录音
***AudioSessionCategoryPlayAndRecord 播放音乐,并录音
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: