how can i play remote .mp3 file in my ios application? - ios

I'm trying to play remote .mp3 file
but its giving the following error.
The operation couldn’t be completed. (OSStatus error -43.)
here is my code :
- (void)viewDidLoad
{
[super viewDidLoad];
isPlaying = NO;
/*
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Dar-e-Nabi-Per" ofType:#"mp3"]];
*/
NSURL *url = [NSURL
URLWithString:#"http://megdadhashem.wapego.ru/files/56727/tubidy_mp3_e2afc5.mp3"];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
}
else
{
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
}
Can anyone please guide me where i'm doing mistake

For steaming audio from a remote server, use AVPlayer instead of AVAudioPLayer.
AVPlayer Documentation
Sample Code:
- (void)playSampleSong:(NSString *)iSongName {
NSString *aSongURL = [NSString stringWithFormat:#"http://megdadhashem.wapego.ru/files/56727/tubidy_mp3_e2afc5.mp3"];
// NSLog(#"Song URL : %#", aSongURL);
AVPlayerItem *aPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:aSongURL]];
AVPlayer *anAudioStreamer = [[AVPlayer alloc] initWithPlayerItem:aPlayerItem];
[anAudioStreamer play];
// Access Current Time
NSTimeInterval aCurrentTime = CMTimeGetSeconds(anAudioStreamer.currentTime);
// Access Duration
NSTimeInterval aDuration = CMTimeGetSeconds(anAudioStreamer.currentItem.asset.duration);
}

Use this to play song from URL
NSData *songData=[NSData dataWithContentsOfURL:url];
self.player = [[AVAudioPlayer alloc] initWithData:songData error:nil];
self.player.numberOfLoops=0;
_player.delegate=self;
[_player prepareToPlay];
[_player play]

Related

Play Audio from URL using AVAudioPlayer

I am Playing Audio from URL given below
"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3"
By Using Code given below
NSString *urlString = #"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3";
NSURL *audioFileLocationURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[audioPlayer setNumberOfLoops:-1];
if (error) {
NSLog(#"%#", [error localizedDescription]);
[[self volumeControl] setEnabled:NO];
[[self playPauseButton] setEnabled:NO];
[[self alertLabel] setText:#"Unable to load file"];
[[self alertLabel] setHidden:NO];
} else {
[[self alertLabel] setText:[NSString stringWithFormat:#"%# has loaded", #"HeadspinLong.caf"]];
[[self alertLabel] setHidden:NO];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
//Load the audio into memory
[audioPlayer prepareToPlay];
}
But I getting Error saying
Printing description of error:
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"
2016-03-08 12:43:45.835 SumeetApp[1839:78581] The operation couldn’t be completed. (OSStatus error 2003334207.)
Can anyone please help me to solve this error or suggest me some other way for playing audio from url.
Thank you
Try This
AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:#"http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"]];
AVPlayerItem *playerItem1 = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player1 = [AVPlayer playerWithPlayerItem:playerItem1];
AVPlayerLayer *playerLayer1 = [AVPlayerLayer playerLayerWithPlayer:player1];
playerLayer1.videoGravity = AVLayerVideoGravityResizeAspectFill;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
playerLayer1.frame = self.view.frame;
});
[self.view.layer insertSublayer:playerLayer1 atIndex:1];
[player1 play];
Hope this work for you.
AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:#"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3"]];
[player play];
Try this code this is working for me.
Try This
NSURL *url = [NSURL URLWithString:#"YOUR_MP3URL"];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player = [AVPlayer playerWithURL:#"YOUR_MP3URL"];
for play
[self.player play];
Hope this helps.
For Error:
you trying to access a file that didn't exist.
so, initWithContentsOfURL:audioFileLocationURL will return nil.
To play Audio:
NSURL *url = [NSURL URLWithString:#"<URL>];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player = [AVPlayer playerWithURL:<URL>];
[player play];

Playing itunes song previews from cocos2d app

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

Memory issue with AVAudioPlayer

For some reason, the cleanupPlayer method is a little buggy and isn't releasing the audio player correctly. My application crashes from time to time, and I suspect it's due to a memory issue. Also, when I try to play an audio file twice (on button click), the second time the audio sometimes cuts out. I'm a bit of a newbie, so any help would be greatly appreciated!
Here is a snippet of code:
.h file:
#property (retain,nonatomic)AVAudioPlayer *player;
.m file:
-(void)playSound:(NSString *)fileName
{
// Play
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:kSoundFileType]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
if(_player != nil) {
[_player release];
}
try this...
-(void)playSound:(NSString *)fileName
{
if (_player.isPlaying) {
[_player stop];
}
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
_player =nil;
}

My apps is crashing when player is play

I have a very simple app that is supposed to only play an audio file on view. Instead my Xcode is crashing.
I am using Xcode version 6. I have implemented the AVFoundation Framework
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"Crowd_cheering"
ofType:#"m4a" ];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
[self.player play];
}
//Try like this with error condition:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Moderato"
ofType:#"mp3"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
}
//Before that add import AVFoundation/AVFoundation.h and add delegate AVAudioPlayerDelegate
//then Implement the AVAudioPlayerDelegate Protocol Methods like this
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
}
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
}
Make sure u connected ur play button properly or not and also check whether you Added an Audio File to the Project Resources properly.

iOS stream audio with no extension

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];

Resources