IOS development-playing local audio (playing in the background), ios background
// Initialize music // create music file path NSString * musicFilePath = [[NSBundle mainBundle] pathForResource: @ "eyeExe" ofType: @ "mp3"]; // determine whether the file exists if ([[NSFileManager defaultManager] fileExistsAtPath: musicFilePath]) {NSURL * musicURL = [NSURL fileURLWithPath: musicFilePath]; NSError * myError = nil; // create a player myBackMusic = [[AVAudioPlayer alloc] initWithContentsOfURL: musicURL error: & myError]; if (myBackMusic = nil) {NSLog (@ "error = % @", [myError description]);} [myBackMusic setVolume: 1]; // sets the volume of myBackMusic. numberOfLoops =-1; // set the number of music playbacks-1 to [myBackMusic prepareToPlay];} // set the screen lock to continue playing [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil];
The corresponding methods include:
/* 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. */
Related parameters:
/* 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 */
Background audio playback method:
1. Add a line of Required background modes to the plist file.
Add an items and set the property to App plays audio or streams audio/video using AirPlay.
As follows:
2. Add the following code:
// Set the screen lock to continue playing [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil]; [AVAudioSession sharedInstance] setActive: YES error: nil];
AVAudioSessionCategoryPlayback is set, indicating that the user ignores switching the mute mode or the screen lock and continues playing the music. And do not play music from other apps. Of course, you can set kAudioSessionProperty_OverrideCategoryMixWithOthers to mix music with other apps.
In addition to AVAudioSessionCategoryPlayback, the following categories are available:
NSString *const AVAudioSessionCategoryAmbient; NSString *const AVAudioSessionCategorySoloAmbient; NSString *const AVAudioSessionCategoryPlayback; NSString *const AVAudioSessionCategoryRecord; NSString *const AVAudioSessionCategoryPlayAndRecord; NSString *const AVAudioSessionCategoryAudioProcessing;
AVAudioSessionCategoryAmbient: In the mute mode or when the screen is locked, music is no longer played, which is mixed with other app sounds.
AVAudioSessionCategorySoloAmbient default mode. It can be used in mute mode or when the screen is locked, and cannot be used together with other apps.
AVAudioSessionCategoryRecord does not play music. The screen lock status continues recording.
AVAudioSessionCategoryPlayAndRecord
When iOS AVAudioPlayer is playing audio, it has downloaded the audio locally. How can I see the following error?
You can try my code. This code can work.
NSData * audioData = [NSData dataWithContentsOfURL: someURL];
NSString * docDirPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
NSString * filePath = [NSString stringWithFormat: @ "% @/%@.mp3", docDirPath, fileName];
[AudioData writeToFile: filePath atomically: YES];
NSError * error;
NSURL * fileURL = [NSURL fileURLWithPath: filePath];
Player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: & error];
If (player = nil ){
NSLog (@ "AudioPlayer did not load properly: % @", [error description]);
} Else {
[Player play];
}
How does one develop a music player for iOS and want to read local iPod music? I don't want to use MPMediaPickerController to select
There is a player that can directly go to the ipod for songs. Under coremedia framework