首页 > 代码库 > iOS开发-播放本地音频(可后台播放)

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

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

    }
    
    //设置锁屏仍能继续播放
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession 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_AVAILABLE(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 AVAudioPlayerDelegate protocol */ 
@property(assign) id<AVAudioPlayerDelegate> 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_AVAILABLE(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_AVAILABLE(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_AVAILABLE(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_AVAILABLE(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_AVAILABLE(10_7, 4_0); /* returns a settings dictionary with keys as described in AVAudioSettings.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.添加如下代码:

    //设置锁屏仍能继续播放
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];


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

NSString *const AVAudioSessionCategoryAmbient;    
NSString *const AVAudioSessionCategorySoloAmbient;    
NSString *const AVAudioSessionCategoryPlayback;    
NSString *const AVAudioSessionCategoryRecord;    
NSString *const AVAudioSessionCategoryPlayAndRecord;    
NSString *const AVAudioSessionCategoryAudioProcessing; 

AVAudioSessionCategoryAmbient 静音模式或者锁屏下不再播放音乐,和其他app声音混合。
AVAudioSessionCategorySoloAmbient 默认模式,静音模式或者锁屏下不再播放音乐,不和其他app声音混合。
AVAudioSessionCategoryRecord 不播放音乐,锁屏状态继续录音
AVAudioSessionCategoryPlayAndRecord 播放音乐,并录音

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