0

I need to play a audio file(mp3) that i am fetching from json in a table view, on clicking row respective song path is passing to another UIView..on loading view it should play.

I know there is a lot of similar problem pasted over internet and i tried many ways nothing worked for me.

Here is the code snippet.

- (void)viewDidLoad
{
     [super viewDidLoad];

     NSError *error = nil;
     [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryAmbient error:&error];
//  audioFile--contains path-- 
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:audioFile ofType:@"mp3"];
     NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSAllLibrariesDirectory, NSUserDomainMask, YES) objectAtIndex:0];

     NSString *filePath = [documentsDirectory stringByAppendingPathComponent:audioFile];

     NSURL *url = [NSURL fileURLWithPath:filePath];

     player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
     if([self.player prepareToPlay])
     {
          NSLog(@"preparing");
     }
     else
     {           
          NSLog(@"some error");
     }
     if([self.player play])
     {
          NSLog(@"playing");
     }
     NSLog(@"not playing");
     NSLog(@"\n\nfile path-> %@\n\n url-> %@",filePath,url);
}

Where player is an object of AVAudioPlayer class

   @property (strong, nonatomic) AVAudioPlayer *player;

From above, Values coming from NSLog() are(for a particular row)

 file path-> /Users/ensignweb/Library/Application Support/iPhone Simulator/6.1/Applications/CE146654-3D1B-4F60-B37D-825267FD6EFB/Library/http:/www.fundamentalalvarado.com/assets/sermons/bible-doctrine-series/033113-pm-Doctrine of Creation vs The Lie of Evolution.mp3

 url-> file://localhost/Users/ensignweb/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/CE146654-3D1B-4F60-B37D-825267FD6EFB/Library/http:/www.fundamentalalvarado.com/assets/sermons/bible-doctrine-series/033113-pm-Doctrine%20of%20Creation%20vs%20The%20Lie%20of%20Evolution.mp3

When i used NSBundle filePath was null so i commented it.Even at the end If Loop escaping to else.I guess there could be the problem.

Please help me out.

mavericks
  • 1,589
  • 16
  • 24
  • You need to **use strong references**. Like this: http://stackoverflow.com/questions/10856332/avaudioplayer-no-sound – Greg Jul 23 '13 at 06:04
  • Do you mean @property (strong, nonatomic) AVAudioPlayer *player;line..Its already strong right. – mavericks Jul 23 '13 at 06:14

4 Answers4

2

This code worked for me

@interface PlayAudioVc : UIViewController<AVAudioPlayerDelegate>
{
//for playback section
    AVAudioPlayer *audioPlayer;
}

-(IBAction) playAudio{
        NSError *error;
        NSURL *url = [NSURL fileURLWithPath:self.audioName];
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        audioPlayer.delegate = self;
        if (error)
            NSLog(@"Error: %@", [error localizedDescription]);
        else
            [audioPlayer play];
}

self.audioName is containing a valid path to audio file

Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
  • Error: The operation couldn’t be completed. (OSStatus error -43.), this error is coming – mavericks Jul 23 '13 at 06:10
  • The problem may be with the audio file path.Log the path and check it – Lithu T.V Jul 23 '13 at 06:12
  • This is one of the audio file path, that is stored in audioName, www.fundamentalalvarado.com/assets/sermons/bible-doctrine-series/052613-pm-The Doctrine of Salvation.mp3, and it is playing in a browser, but while running in simulator OSStatus error is coming. – mavericks Jul 23 '13 at 06:26
  • Well check the path again the issue appeared to me in the path to url ..If the url is correct it **must** work – Lithu T.V Jul 23 '13 at 06:37
  • I tried with another mp3 file by saving it locally, then also it is not playing..Does it run on simulator or not..I am new to this..so not able to find where is the problem .. – mavericks Jul 23 '13 at 08:27
1

I do this in my app and it works like a charm

/**
 *  This method plays the 'pop' sound during the animation.
 */
-(void) playSound : (NSString *) fName : (NSString *) ext
{
    NSString *path  = [[NSBundle mainBundle] pathForResource : fName ofType :ext];
    if ([[NSFileManager defaultManager] fileExistsAtPath : path])
    {
        NSURL *pathURL = [NSURL fileURLWithPath : path];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
        AudioServicesPlaySystemSound(audioEffect);
    }
    else
    {
        NSLog(@"error, file not found: %@", path);
    }
}

You need to import #import AVFoundation/AVFoundation.h and the respective framework.

Go to project summary and build phases tab under that go to copy bundle resources. enter image description here

Under copy bundle resources check whether the audio file exists.

Satheesh
  • 10,998
  • 6
  • 50
  • 93
  • Check whether the resource file is inside your resource bundle? – Satheesh Jul 23 '13 at 07:02
  • When i tried with locally saved mp3 file then it worked and file was there in bundle resource but that path was not there... – mavericks Jul 23 '13 at 11:16
  • suppose this is the url-> http://www.fundamentalalvarado.com/assets/sermons/bible-doctrine-series/051213-pm-The Doctrine of the Forgiveness of Sin.mp3, how this would play – mavericks Jul 23 '13 at 11:17
  • This would not play by the above function, you should download the file and try to play or try AVAudioPlayer initWithContentsOfURL to achieve this. – Satheesh Jul 23 '13 at 11:40
  • In web view it is opening perfectly..but in AVAudioPlayer same...- (void)viewDidLoad { [super viewDidLoad]; audioFile = [audioFile stringByReplacingOccurrencesOfString:@" " withString:@"%20"]; // [audWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:audioFile]]]; NSURL *url=[NSURL URLWithString:strAudFile]; audPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil]; if([audPlayer play]) { NSLog(@"ok"); } NSLog(@"not playing"); } ...."not playing" – mavericks Jul 23 '13 at 12:48
1

Try this one,

Include AVFoundtion.Framework and import into AVFoundation/AVFoundation.h into ViewController and Add AVAudioPlayerDelegate in '.h' file.

Then create object for AVAudioPlayer class

@property (nonatomic, retain) AVAudioPlayer *audioPlayer;

NSString *path = [[NSBundle mainBundle]pathForResource:@"AIRTEL" ofType:@".MP3"];
NSURL *url = [NSURL fileURLWithPath:path];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
               initWithContentsOfURL:url
               error:&error];
if (error)
{
    NSLog(@"Error in audioPlayer: %@",
          [error localizedDescription]);
} else {
    audioPlayer.delegate = self; 
    [audioPlayer prepareToPlay];
    [audioPlayer play];

}

Hope this would help.

mavericks
  • 1,589
  • 16
  • 24
Yas
  • 1,064
  • 9
  • 13
0

Your URL looks strange:

url-> file://localhost/Users/ensignweb/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/CE146654-3D1B-4F60-B37D-825267FD6EFB/Library/http:/www.fundam

it starts with file:// and contains http:/

RRZ Europe
  • 954
  • 3
  • 14
  • 31
  • In audioFile it has only url path that start with http://, I tried with audioFile, OSStatus error -43, error came. Then I tried with NSBundle, it was giving null value, so I tried NSearchPath...** in a hope that i could get path that might stored json path and play it locally then.I am new to this so, I don't know where i'm wrong or right. – mavericks Jul 23 '13 at 06:34
  • since you want to play a remote mp3, you should try [NSURL URLWithString:string_with_url] – RRZ Europe Jul 23 '13 at 08:32
  • I tried with individual URL, NSURL *url = [NSURL URLWithString:@"http://www.fundamentalalvarado.com/assets/sermons/bible-doctrine-series/051213-pm-The Doctrine of the Forgiveness of Sin.mp3"];, url contains null value. – mavericks Jul 23 '13 at 11:14
  • your path contains spaces, thus the null values – RRZ Europe Jul 23 '13 at 14:20
  • whats not clear to me is where you hold your mp3... do you copy it to your application in the same path that your json provides? Then I would just use the filename from the json, strip the spaces out of it and put a copy of the mp3 with no spaces in the name into your app – RRZ Europe Jul 23 '13 at 14:23
  • if you want to play a remote mp3, try to replace the spaces with %20 – RRZ Europe Jul 23 '13 at 14:28
  • I did that too, It is there in last comment of @satheeshwaran, still it is just escaping [playerObj play]..json path is in a string variable 'audioFile' and that only i have been using. – mavericks Jul 24 '13 at 05:51
  • I would try to hard code an existing mp3 that does not contain spaces from the web and try if that works (eg. @"h ttp://www.some.com/any.mp3" ... w/o the space between the http, needed to put it so it shows) – RRZ Europe Jul 24 '13 at 07:43