iOS開發-播放本地音頻(可後臺播放) – iPhone手機開發技術文章 iPhone軟體開發教學課程

//初始化音樂
    //創建音樂文件路徑
    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 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.添加如下代碼:vcD48cD48cHJlIGNsYXNzPQ==”brush:java;”> //設置鎖屏仍能繼續播放
[[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 播放音樂,並錄音

發佈留言