i have to play a file which we get from a server.I have to download the file asynchronously and save it in documents directory.Here is what i tried:
NSData * _objectData = [NSData dataWithContentsOfURL:url];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
audioPlayer.numberOfLoops = 1;
if (audioPlayer == nil)
NSLog(#"%#",error.description);
else
[audioPlayer play];
Use Mattgallagher's AudioStreamer for streaming mp3.
For downloading follow these link.
#Enjoy.
Related
Here is my code, In this first I am calling mp3 url for downloading the audio data. then I am saving that data in local directory, After that I am playing audio from local file path but its not working AVAudioPlayer throwing error. I have tried some other ways also but no one work for me.
On simulator same code is working fine.
And the audio url is playing like a charm in browser.
NSURL *urlll=[NSURL URLWithString:#"www.xyz.audio.mp3"];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:urlll] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responce,NSData* data,NSError * error) {
if (error == nil)
{
indicator.hidden=YES;
[indicator stopAnimating];
if (data)
{
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.mp3", docDirPath , #"Audio"];
[data writeToFile:filePath atomically:YES];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
AudioPlayer.delegate=self;
[AudioPlayer prepareToPlay];
if (AudioPlayer == nil) {
NSLog(#"AudioPlayer did not load properly: %#", [error description]);
} else {
[AudioPlayer play];
}
}
}
}];
But I am getting these kind of errors : Error Domain=NSOSStatusErrorDomain Code=1685348671 "The operation couldn't be completed. (OSStatus error 1685348671.)
Please Help me :( .
In your code you save the audio to NSString *filePath but you initiate with fileURL. Could it be that you actually wanted to do this:
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:&error];
If not then you should know that the error is reporting to you a kAudioFileInvalidFileError. Which means the file is malformed. You could try other formats like .caf or .aifc or aiff.
--edit--
Make sure the AVAudioPlayer is a property in .m or .h file, so the memory allocation lasts after leaving the method:
#property (nonatomic,strong) AVAudioPlayer *AudioPlayer;
(side note: properties should start with lowercase -> audioPlayer)
I’m trying to play a music with volume normalization, applyied by iVolume.
The music play 1 or 2 seconds and just after apply the volume normalization. Apparently the music is correctly, on native iPod player works fine.
After two days searching and testing, I can’t find any solution or tips.
I’m using AVAudioPlayer, because I need to get external audios.
Follow the music:
https://db.tt/52qohzJn
Piece of code:
NSError *setCategoryError = nil;
NSError *setAVError = nil;
NSString *path = [NSString stringWithFormat:#"%#/02GreenDay.m4a", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath: path];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundUrl error:&setAVError];
NSLog(#"Error: %#",[setAVError localizedDescription]);
AVAudioSession *session = [AVAudioSession sharedInstance];
if (![session setCategory:AVAudioSessionCategoryPlayback
error:&setCategoryError])
{
NSLog(#"%#",[setCategoryError localizedDescription]);
NSLog(#"Error AudioSession");
}
[session setActive:YES error:nil];
[_audioPlayer prepareToPlay];
[_audioPlayer play];
The _audioPlayer is a property.
Any ideas?
Thanks!
I am trying to get itunes song previews to play in my app. I have found some other questions like this but none of the solutions have worked for me. I am already signed up with the Affiliate program that apple has. Here are some of the things I have tried:
This got me the itunes preview URL that I am trying
NSUInteger numberOfResults = 200;
NSString *searchString = #"AC/DC";
NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalSearchString = [NSString stringWithFormat:#"https://itunes.apple.com/search?term=%#&entity=song&limit=%u",encodedSearchString,numberOfResults];
NSURL *searchURL = [NSURL URLWithString:finalSearchString];
dispatch_queue_t iTunesQueryQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions);
dispatch_async(iTunesQueryQueue, ^{
NSError *error = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:searchURL options:NSDataReadingUncached error:&error];
if (data && !error) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *array = [JSON objectForKey:#"results"];
NSLog(#"Array is:%#",array);
}
});
This plays nothing
NSURL *url = [NSURL URLWithString:[_backgroundPreviewList objectAtIndex:randomPreview]];
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];
}
This also played nothing
AVPlayer* aPlayer = [AVPlayer playerWithURL:url];
[aPlayer play];
I even tried this that didn't work
MPMoviePlayerController* player = [[MPMoviePlayerController alloc] initWithContentURL:url];
[player play];
If anyone has done this can they let me know how to play the songs.
This is released and working using MPMoviePlayerController, which I believe is the recommended approach for the streaming previews. Depending on what you are trying to do, you might have to work through some steps to enable play in the background. Good luck. p.s. if you get the AVPlayer working there are more docs available with solutions for background play see Technical QA doc 1668 from Apple
{
self.songPreview = [[MPMoviePlayerController alloc] init];
self.songPreview.movieSourceType = MPMovieSourceTypeStreaming;
/// set your URL from wherever you are getting it
[self.songPreview setContentURL:self.previewArtWorkButton.currentPreviewURL];
[self.view addSubview:self.songPreview.view];
/// i have set this next property to hidden because i am controlling volume and play programmatically
[self.songPreview.view setHidden:YES];
/// i have this next property set to No because I am using another trigger to play the /// song and not auto play after the buffering has completed
[self.songPreview setShouldAutoplay:NO];
[self.songPreview prepareToPlay];
}
/// later i call the play method
[self.songPreview play];
I have got it working. One of the things I changed is I took that specific class out of ARC to make sure things were staying around. Here is the code I am using now
NSURL *url = [NSURL URLWithString:#"URL"];
AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:url];
NSLog(#"The url is: %#", url);
if(_player)
{
[_player release];
}
_player = [[AVPlayer playerWithPlayerItem:playerItem] retain];
[_player play];
_player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
Where _player is an AVPlayer object
I have two pieces of code:
Code 1 - This is playing a music file via the in-ear speaker:
NSString *tileDirectory = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"8Ocean.mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:tileDirectory];
NSError *error=nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if(!error)
{
[self.audioPlayer prepareToPlay];
UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
[self.audioPlayer play];
}
else
{
NSLog(#"%#",error.localizedDescription);
}
Code 2- This is playing a music file during a phone call (is routed to in-ear or speaker phone depending on user setting during the phone call)
NSString *tileDirectory = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"8Ocean.mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:tileDirectory];
NSError *error=nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if(!error)
{
[self.audioPlayer prepareToPlay];
self.audioPlayer.volume=10.0;
UInt32 sessionCategory = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
[self.audioPlayer play];
}
else
{
NSLog(#"%#",error.localizedDescription);
}
My issue is:
Code 1 and 2 work well independently. However, after using code 1, code 2 will not work at all (unless the app is killed and restarted)
I have tried everything I can think of but cannot work out where the problem is from.
Your app needs to handle audio session interruptions from phone calls in order for audio processing not to be killed for your app.
I am looking to play a live audio stream within my app using AVAudioPlayer or AVPlayer, however the link has no extension and so whenever I try to set it up, it fails. Does anyone have any suggestions?
Code:
NSString *path = #"http://audio7.radioreference.com/24705802";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]];
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:&error];
player.volume = 1.0f;
player.numberOfLoops = -1.0f;
[player prepareToPlay];
if (player == nil) {
NSLog(#"Error: %# Description: %#", error.localizedDescription, error.description);
}
else {
[player play];
}
NSData does not constitute a stream, but static data (eg sound data that you created or data loaded from a file). You want to create an AVPlayer object with an NSURL pointing to the stream. For example:
AVPlayer *player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:path]];
[player play];