Download and play mp3 file from url with iphone application - iphone

We want to create an application that downloads a mp3 file and then starts to play it.
Has anyone an idea of how to download the mp3 file from an url and then store it, either on the iphone or in the application (depending on what is possible).

Add the following import statement to your header:
#import <AVFoundation/AVFoundation.h>
In your implementation somewhere:
NSError *error;
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://xyz/abc.mp3"]];
audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
audioPlayer.numberOfLoops = -1;
audioPlayer.delegate = self;
audioPlayer.volume = 1.0f;
[audioPlayer prepareToPlay];
if (audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[audioPlayer play];
Don't forget to release the player at some point:
[audioPlayer release];

dirt simple, on a thread:
myMP3 = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://..."]];
slightly less simple, but with more options:
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://..."]] delegate:self];
Or just play it directly:
[[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://..."] error:nil] play];
Edit: the above snippet would leak. You should store the created AVAudioPlayer instance in a member and release it when the audio finishes playing or you are otherwise done with it. I do not know off hand if releasing a playing AVAudioPlayer stops the audio.

Related

Play audio without buffer

I am playing an audio file in my iphone app,I fetch the audio from a url.While playing it stops for a while to buffer.
How can I make playing audio without any buffer or play after loaded fully ?
-(void) playAudio2
{
NSURL *url = [NSURL URLWithString:#"http:domain/iphonetest/mp3/sol.mp3"];
NSData *data = [NSData dataWithContentsOfURL:url];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
[audioPlayer setVolume:1];
[audioPlayer play];
}
Try using NSURLConnection or AFNetworkingKit to download the file (There is lots of resources show how to download a file. Just search for it).
Then in the -(void)connectionDidFinishLoading:(NSURLConnection *)connection delegate method for NSURLConnection or in the completionBlock for AFNetworkingKit, play the file like your code. But use NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file] for initializing url and use [audioPlayer prepareToPlay] before playing that.

iphone dev mp3 file not playing using av audio player

i am trying to play an mp3 audio file, the file will be uploaded by user on web server and i will get the url of that file and then i have to play that file but i am not succeeding in it. here is my code
NSURL *url = [NSURL URLWithString:url1];
NSData *theData = [NSData dataWithContentsOfURL:url];
newPlayer = [[AVAudioPlayer alloc] initWithData:theData error:nil];
[newPlayer play];
the url is like this
http://mqm.designers99.com/Notification/mp3_files/1331551313_1919.mp3
Plz. guide me coz i am stuck here, thanx and regards
Try 'reading' the error:
NSURL *url = [NSURL URLWithString:url1];
NSData *theData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
newPlayer = [[AVAudioPlayer alloc] initWithData:theData error:&error];
if (error == nil) {
NSLog(#"AVAudioPlayer start playing");
[newPlayer play];
} else {
NSLog(#"%#", error);
}
Any "luck" ?
Include AVFoundation and AudioToolBox frameworks
Import header for that framework in .h file
#import<AVFoundation/AVFoundation.h>
#import<AudioToolbox/AudioToolbox.h>
Instantiate AVAudioPlayer,
AVAudioPlayer *player
Use this code for play audio.It's working fine for me
NSString *url1=#"http://mqm.designers99.com/Notification/mp3_files/1331551313_1919.mp3";
url1=[url1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//Encode your url
NSLog(#"after encoding========:%#",url1);
NSURL *url = [NSURL URLWithString:url1];
NSData *theData = [NSData dataWithContentsOfURL:url];
player = [[AVAudioPlayer alloc] initWithData:theData error:nil];
[player play];
Edit:Without encode the url you given also played well.

Get an audio stream from URI and play it on iPhone

I would like to get an audio stream from URL and play it on iPhone. Unfortunately, there is only C# example of how to play that stream, but I need a realization on Objective C in iPhone frameworks. I have tried my self to use different audio frameworks but it was all unsuccessful. This is what in C#:
response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (SoundPlayer player = new SoundPlayer(stream))
{
player.PlaySync();
}
}
What should I do in objective C to get a stream audio from that url? In that URL I don't have an mp3 file or something, I just get a stream. Probably I must somehow download that stream to an iPhone audio file and then play it to get rid of lags.
I tried this:
AVPlayer *player = [AVPlayer playerWithURL:url];
[player play];
And this:
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: url error:nil];
[theAudio setVolume :0.50]; //setting the volume
[theAudio play];
Neither worked.
I have tested my url, it works well in browser.
This is the code that worked:
NSData *_objectData = [NSData dataWithContentsOfURL:url];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
audioPlayer.numberOfLoops = 0;
audioPlayer.volume = 1.0f;
[audioPlayer prepareToPlay];
if (audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[audioPlayer play];
NSString* resourcePath = url; //your url
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
NSError *error;
app.audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
app.audioPlayer.numberOfLoops = 0;
app.audioPlayer.volume = 1.0f;
[app.audioPlayer prepareToPlay];
if (app.audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[app.audioPlayer play];
Hey I faced this problem of audio streaming for a radio application. I had searched for the answers and they did not work. AVAudioPlayer is not the class to be used here. Downloading the contents of URL using NSData object is not the solution either as it downloads the contents then the code further executes. It is similar to downloading a mp3 and then playing it locally on a player.
[NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]]; //Downloads the contents of the url and in case of radio the url's content is unlimited. The program gets frozen on executing this.
Instead use AVPlayer class.
This code worked in my radio application
AVPlayer *objAVPlayer = [[AVPlayer alloc] initWithURL:url];
[objAVPlayer play];
This code does not download the contents at the url but it plays the stream as it is received.
Look into the AVPlayer class, part of the AVFoundation framework... this is the objective-c (iOS) class you use for streaming audio.
MPMoviePlayerController *player;
player = [[MPMoviePlayerController alloc] init] ;
player.view.frame = CGRectMake(0, 0, 0, 0);
player.movieSourceType = MPMovieSourceTypeStreaming;
player.view.hidden = YES;
[self.view addSubview: [wikiMusicPlayer view]];
NSString *address = Your URL;
address = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:address];
[wikiMusicPlayer setContentURL:url];
[wikiMusicPlayer prepareToPlay];
[wikiMusicPlayer setShouldAutoplay: NO];
[wikiMusicPlayer play];

restarting a (audio) loop after it has finished

I want to play an audio loop by turning on a switch but i do not want the loop to end until the switch is turned off. When the loop ends i want it to simply start back at the beginning as to be continuos.
Try something like this. Note the -1 tells the music to repeat indefinitely:
Import this file at the top of your file:
#import <AVFoundation/AVFoundation.h>
Then to use it:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:resourcePath ofType:#"caf"];
NSError *activationError = nil;
NSError *audioPlayerInitError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];
NSURL *newURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError];
[newPlayer prepareToPlay];
[newPlayer setVolume:.8];
[newPlayer setNumberOfLoops:-1]; // -1 means play indefintely
[newPlayer setDelegate: self];
[newPlayer play];
[newPlayer release];
And then to stop it you would do:
if ([newPlayer isPlaying]) {
[newPlayer stop];
}

playing audio files from table, iphone

I've created a list of music file names in an array which is used to populate an uitableview. I want to make the audio player take this array or table as the playlist and play them continuously one by one, with all the features like play, pause, next, previous, forward, backward and stop. What is the best way to implement this. All the music files in the resource folder itself so that i can initiate each one as
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"mp3"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = newURL;
[newURL release];
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
self.appSoundPlayer = newPlayer;
[newPlayer release];
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
Could this be as simple as implementing the AVAudioPlayerDelegate?
appSoundPlayer.delegate=self;
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (successfully)
{
// play next track
}
}
Obviously you'd need to keep track of which track is currently playing in order to work out the next track to play, but that shouldn't be a problem. You'd also have to implement your own controls and logic for track skip etc, but again this is easily done.