How to play the iPod Library file in the AVPlayer - iphone

How can I get an ipod library music file into AVAudioPlayer?

As David mentions there is more work to do than this, for example you have to manage playing the next track in a collection of media items, but here is one way to do it with a set of MPMediaItems that a user selected from the iPod Picker. The AssetURL is what you use, it gives you a path to the MP3 file (e.g. ipod-library://item/item.mp3?id=-6889145242935454020)
NSURL *anUrl = [[mediaItems objectAtIndex: 0] valueForProperty:MPMediaItemPropertyAssetURL];
self.audioPlayerMusic = [[[AVPlayer alloc] initWithURL:anUrl] retain];
[self.audioPlayerMusic play];

Yes, you can play songs from the iPod library using the SDK without resorting to the MPMusicPlayerController class.
The more basic AVPlayer class can handle audio files from the iPod library by using the NSUrl value from the song's MPMediaItemPropertyAssetURL property. You have to do a lot more work to get everything setup properly, but it can be done.

The SDK has no provision for reading files from the iPod library (as you'd need to do to use AVAudioPlayer with it), probably for anti-piracy reasons. To play iPod library items, use the MPMusicPlayerController class.
Edit: This is no longer accurate. See the below answers which describe the use of the AVPlayer class.

Is there any possibility to get information about dB-metering in MPMusicPlayerController? Perhaps initiating an AVAudioSession for Recording in parallel would do the job?? I need dB-values to build some kind of volume-spectrograph.

- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {
NSURL *url = [[mediaItemCollection.items objectAtIndex:0] valueForProperty:MPMediaItemPropertyAssetURL];
NSError *error;
self.player = [[AVAudioPlayer alloc] url error:&error];
if (!error) {
[self.player prepareToPlay];
[self.player play];
}
[mediaPicker dismissModalViewControllerAnimated:YES];
}

Related

how to play sound file which is on my web server and run in background when user click "Home" button...?

I'm new to audio handling in ios.
1.I want to know that if I have web server on which I have some audio files. And through my iOS application user can play that file, allow them to forward or reverse functionality, pause etc.
2.And when user click on "Home" button sound file not pause or stop at that time, file play in background uptill user not close the application properly...
main thing is application play file online and not whole file download on user device
if any of the one answer is possible plz help
Thanks
Streaming Audio Services is possible. you should using a AVPlayer(not AVAudioPlayer AVAuioPlayer is not available Streaming Services.)
This apple Sample Code StitchedStreamPlayer is good for you.
This code Streaming Movie Play Sample, but also available Audio Service.
Your best bet is to user this github project https://github.com/jfricker/AudioStreamer
You can control forward and reverse for audio in it. I have used this in one of my project and the performance is really good.
after searching things here I'm with answer.for run application in background playing songs, step is as below
in your application info.plist file add "Application does not run in background" to "YES"
in your application info.plist file add "YES"Required background modes" and set "App plays audio"
in your .m file
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"select" ofType:#"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
if (error)
{
NSLog(#"Error in audioPlayer: %#", [error localizedDescription]);
} else {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer play];
}
}

Keep UIWebView playing music while App is in background

I think everything is in the title.
I have a UIWebiew that plays music, and when the user use the power or home button, putting the app in background, I want the music to keep playing.
Is it possible ?
Thank you for your help !
You can't actually do this with a UIWebView, but you can still do it. This method still streams the audio off of an online resource via a URL. Here is some code to help you. Now, lets say, you want to stream the audio when the app exits for a video, then its very similar, but uses the MediaPlayer framework instead of AVAudioPlayer framework.
NSURL *url = [NSURL URLWithString:#"http://website.com/audio.mp3"];
NSData *data = [NSData dataWithContentsOfURL:url];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
[audioPlayer play];
A little tricky but it is possible. From the official Apple doc below:
https://developer.apple.com/library/ios/qa/qa1668/_index.html
You need to first declare in your plist the UIBackgroundModes for audio, and then write the following code snippet in your AppDelegate
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (!success) { /* handle the error condition */ }
NSError *activationError = nil;
success = [audioSession setActive:YES error:&activationError];
if (!success) { /* handle the error condition */ }
Now when you have audio playing from a UIWebView, you can go to the home screen, change to another app, or lock the screen and the audio will continue playing.
I don't believe this is possible, and even after checking UIWebView's documentation I only found the following three attributes related to media playback.
allowsInlineMediaPlayback property
mediaPlaybackRequiresUserAction property
mediaPlaybackAllowsAirPlay property
Unfortunately, none of them do this.
Yes it is possible. You need to do:
Activate playback session:
#import AVFoundation;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
Add audio background mode in your Info.plist:
Required background modes: App plays audio or streams audio/video using AirPlay
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>

AVAudioPlayer Help: Playing multiple sounds simultaneously, stopping them all at once, and working around Automatic Reference Counting

I am trying to create buttons that play single sound files and one button that stops all of the sounds that are currently playing. If the user clicks multiple buttons or the same button in a short amount of time, the app should be playing all of the sounds simultaneously. I have accomplished this without much difficulty using the System Sound Services of iOS. However, the System Sound Services play the sounds through the volume that the iPhone's ringer is set to. I am now trying to use the AVAudioPlayer so that users can play the sounds through the media volume. Here is the code that I am currently (yet unsuccessfully) using the play the sounds:
-(IBAction)playSound:(id)sender
{
AVAudioPlayer *audioPlayer;
NSString *soundFile = [[NSBundle mainBundle] pathForResource:#"Hello" ofType:#"wav"];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile] error:nil];
[audioPlayer prepareToPlay];
[audioPlayer play];
}
Whenever I run this code in the iPhone Simulator, it does not play the sound but does display a ton of output. When I run this on my iPhone, the sound simply does not play. After doing some research and testing, I found that the audioPlayer variable is being released by Automatic Reference Counting. Also, this code works when the audioPlayer variable is defined as an instance variable and a property in my interface file, but it does not allow me to play multiple sounds at once.
First thing's first: How can I play an infinite number of sounds at once using the AVAudioPlayer and sticking with Automatic Reference Counting? Also: When these sounds are playing, how can I implement a second IBAction method to stop playing all of them?
First off, put the declaration and alloc/init of audioplayer on the same line. Also, you can only play one sound per AVAudioPlayer BUT you can make as many as you want simultaneously. And then to stop all of the sounds, maybe use a NSMutableArray, add all of the players to it, and then iterate though and [audioplayer stop];
//Add this to the top of your file
NSMutableArray *soundsArray;
//Add this to viewDidLoad
soundsArray = [NSMutableArray new]
//Add this to your stop method
for (AVAudioPlayer *a in soundsArray) [a stop];
//Modified playSound method
-(IBAction)playSound:(id)sender {
NSString *soundFile = [[NSBundle mainBundle] pathForResource:#"Hello" ofType:#"wav"];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile] error:nil];
[soundsArray addObject:audioPlayer];
[audioPlayer prepareToPlay];
[audioPlayer play];
}
That should do what you need.

Unable to play audio on device (iOS)

I am using the following code to play a audio in iOS using **AVAudioPlayer** class.
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"myAudio" ofType:#"mp3"];
NSURL *audioURL = [[NSURL alloc] initFileURLWithPath:audioPath];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer play];
This is working fine in simulator. But, i am not getting the sound output when i run it on the device. The delegate methods ofAVAudioPlayerDelegate are also being called but there is no volume output. Where am i going wrong here.... Another important aspect i'v noticed here is that, i am getting a large message in my GDB while playing the audio file on simulator. But the same thing is not happening on device... Please refer the screenshot below for GDB messages while running on the simulator.
Check if your device is on loudspeaker mode or not..
to listen the sound through Loundspeaker use this -
// set audio to loudSpeaker mode for iphone
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
or you can increase the volume of your audio file using this -
Player.volume = 10.0;
Have you tried the .caf or .wav file? might possible that .mp3 is not working on iPhone. Also check the duration of your file not greater than 30 sec.
I was so so stupid.... My volume button was turned off. That was the reason.
Really sorry for wasting your time guys... My sincere apologies.

Playing continuos sound in iPhone app

I have an iPhone application which requires me to play a looping mp3 sound during the entire lifetime of app.
But based on some actions performed by user this mp3 should stop/pause for while & another mp3 should play & then this mp3 should resume playing again.
I havent really used any audio API on iPhone yet, I've just used AudioToolbox for playing sounds on button taps thats all.
So what do you guys recommend I should do.
Any pointers...? suggestions....?
just as I wrote in this post, you can use AVAudioPlayer
code extract:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"mySound" ofType:#"mp3"];
NSURL *soundFileURL = [NSURL URLForString:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:soundFileURL];
player.numberOfLoops = -1; //infinite
[player play];
and you can pause it with:
[player pause];