I've been trying to get this to work all day. I've tried everything I could think of to get this to work. I have a song which is an m4a located on a server. I download it and save it to the documents directory and then play it with AVAudioPlayer. When I tap the UIButton to play the song, it doesn't do anything. I am logging the NSError but its returning a (null). Here is my code.
NSError *error;
NSURL *url = [NSURL URLWithString:#"http://a2.mzstatic.com/us/r30/Music/43/49/2e/mzi.ittnbeif.aac.p.m4a"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *file = [NSString stringWithFormat:#"%#/in-my-life.m4a", documents];
[data writeToFile:file atomically:YES];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:file] error:&error];
[player setVolume:1.0];
[player setDelegate:self];
[player setMeteringEnabled:YES];
[player play];
NSLog(#"Play Song: %#", file);
NSLog(#"Error: %#", error);
This is what the log shows.
2011-08-01 17:34:09.659 APP[1275:707] Play Song: /var/mobile/Applications/B1F04C1F-1541-4EDB-B898-264061292EDB/Documents/in-my-life.m4a
2011-08-01 17:34:09.661 APP[1275:707] Error: (null)
Any ideas?
Related
I have an URL which I get from JSON response, When I hit the URL in browser the file is downloaded, Now am wondering how can I play such URL which is a Download URL.I've been looking around many post But none of them could help me.
type of url am getting : http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1
Below is the code I tried.
NSString *audio=[NSString stringWithFormat:#"%#.mp3",cell.url];
NSLog(#"url:%#",audio);
NSURL *url = [NSURL fileURLWithPath:audio];
NSData *soundData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:#"sound.caf"];
[soundData writeToFile:filePath atomically:YES];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL
fileURLWithPath:filePath] error:&error];
[_audioPlayer play];
NSLog(#"error %#", error);
Try this:
//download your audio file
NSString *urlString = #"http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1.mp3";
NSURL *url = [NSURL fileURLWithPath:urlString];
NSData *soundData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:#"sound.caf"];
[soundData writeToFile:filePath atomically:YES];
// get the file from directory
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *soundPath = [documentsDirectory stringByAppendingPathComponent:#"sound.caf"];
NSURL *soundUrl;
if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath])
{
soundUrl = [NSURL fileURLWithPath:soundPath isDirectory:NO];
}
// play audio file
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
[audioPlayer prepareToPlay];
[audioPlayer play];
You should download your audio file asynchronously.
Thank You Dipankar Das for you help.
I am posting the whole solution here.
which worked for me absolutely.
NSString *audio=#"http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1.mp3";
NSURL *url = [NSURL URLWithString:audio];
NSData *soundData = [NSData dataWithContentsOfURL:url];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:#"sound.caf"];
[soundData writeToFile:filePath atomically:YES];
// get the file from directory
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *soundPath = [documentsDirectory stringByAppendingPathComponent:#"sound.caf"];
NSURL *soundUrl;
if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath])
{
soundUrl = [NSURL fileURLWithPath:soundPath isDirectory:NO];
}
// plau audio file
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
[_audioPlayer prepareToPlay];
[_audioPlayer play];
[_audioPlayer setVolume:5.0];
try use AVPlayer or AVPlayerViewController, you can use direct URL to play mp3 files
even with local file as you will first download it to device, then play from local URL
do not forget that object AVPlayer has to be as property of your Class not local object because of auto-releasing, so declare your player variable in class and set in function not just locally in function and try to play ...
[update]
more details how to do it -> How to play video with AVPlayerViewController (AVKit) in Swift
Here is the mistake
NSString *audio=[NSString stringWithFormat:#"%#.mp3",cell.url];
NSURL *url = [NSURL fileURLWithPath:audio];
I assume that it is a remote url and you cannot treat it as a file url. So you must use
NSURL *url = [NSURL urlWithString:audio];
i'm trying to design audio streaming app everything is working, but i don't know how to download audio file to the device and read it afterword.
Download audio to document directory.
play it back from document directory.
Added code:
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path firstObject];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:#"evet.mp3"];
// UIImage *cellImage = [[UIImage alloc] initWithContentsOfFile:filePath];
NSLog(#"%#",filePath);
NSError *error;
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_objectData error:&error];
[audioPlayer play];
Based on the code you posted try this.
Change
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_objectData error:&error];
to this:
NSURL *fileURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
AVAudioPlayer wants a URL object (which needs to be a local URL not a remote web address, hence fileURLWithPath:) not the data itself.
You were trying to give the NSData itself to the audio player.
Fetch your audio file in document directory
- (NSString *)getCacheDirectoryPathForAudio:(NSString *)filePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp3", filePath]]; //add
return fullPath;
}
Initiate player with file path
NSString *pathToSaveAudioString = [self getCacheDirectoryPathForAudio:#“filename”];
NSURL* url = [NSURL fileURLWithPath:pathToSaveAudioString];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pathToSaveAudioString];
if (fileExists) {
NSError* error = nil;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[self.player setDelegate:self];
if(!self.player)
{
NSLog(#"Error creating player: %#", error);
}
}
else
{
NSLog(#“File Not Exist: %#");
}
and play it using
[self.player play];
Use Delegate methods to check status
#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
}
For more details follow
http://iosdeveloperzone.com/2012/10/01/tutorial-playing-audio-with-avaudioplayer/
I have simple code
NSData *D = [self FindDatafromDocument:#"ASDF"];
player = [[AVAudioPlayer alloc] initWithData:D error:nil];
[player setDelegate:self];
[player play];
Method
- (NSData *)FindDatafromDocument:(NSString *)Name {
NSData *IMG;
NSError *error;
NSArray *directoryContents = [[NSArray alloc] init];
directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[Utility getDocumentDirectory] error:&error];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",Name];
NSArray *ArrImages = [directoryContents filteredArrayUsingPredicate:predicate];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *Doc = [paths objectAtIndex:0];
for (NSString *imageName in ArrImages) {
if ([imageName rangeOfString:#".caf"].location != NSNotFound) {
IMG = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:#"%#/%#",Doc,imageName]];
}
}
return IMG;
}
Hi I have a setup that records audio (with AVAudioSessionCategoryPlayAndRecord category), now I want to playback and MP3 file as usual with AVAudioPlayer instance, but no any sound can be hear.
AVAudioPlayer do not throw any error, nor in its delegate callbacks.
Has anybody similar experience? How to overcome this?
Please use this -
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#.mp3", docDirPath , #"Welcome"];
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if (avPlayer == nil)
{
NSLog(#"AudioPlayer did not load properly: %#", [error description]);
}
else
{
[avPlayer play];
avPlayer.delegate=self;
}
And tell me if it is working or not.
I have a UITableView displaying a llist f files in the Documents Directory... and I want it to play the audio file in the Documents directory when pressed...
It runs with no errores but doesn't play the audio when pressed...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.caf",indexPath.row+1]];
NSURL *audioURL = [NSURL URLWithString:fileName];
NSData *audioData = [NSData dataWithContentsOfURL:audioURL];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
_audioPlayer.delegate = self;
[_audioPlayer play];
}
Change this line:
NSURL *audioURL = [NSURL URLWithString:fileName];
to this:
NSURL *audioURL = [NSURL fileURLWithPath:fileName isDirectory:NO];
And then just do:
if(_audioPlayer == nil)
{
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
}
else
{
_audioPlayer = [self.audioAlert initWithContentsOfURL:audioURL error:nil];
}
To start out, the best way to declare a files path is this
- (NSString *)docsdir {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
}
in your header, declareNSString *Path;
then, declare the path like this when the view loads
Path = [[self docsdir]stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.caf",indexPath.row+1]];
if (![[NSFileManager defaultManager]fileExistsAtPath:Path]) {
[[NSFileManager defaultManager]copyItemAtPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:#"%d",indexPath.row+1] ofType:#"caf"] toPath:Path error:nil];
}
now to play it, do this
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:&error];
player.delegate = self;
[player play];
I would like to play a sound file retrieved from my server, as a base 64 encoded file.
So far, I have decoded the file using base64 and written it to a file as so:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"voicemail.wav"]];
[fileManager createFileAtPath:filepath contents:[responseDict objectForKey:#"ResponseData"] attributes:nil];
However, I am having trouble actually playing the sound file. My code returns the error:
The operation couldn't be completed. OSStatus error 2003334207.
Please can you tell me where I am going wrong?
NSURL * url = [NSURL fileURLWithPath:filePath];
AVAudioPlayer *sound = [[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err] autorelease];
if (! sound) {
NSLog(#"Sound had error %#", [err localizedDescription]);
} else {
[sound prepareToPlay];
[sound play];
}
#Himanshu
As suggested by the Mattias Wadman, I tried to play downloaded file using vlc/iTunes media player and the file were not playing.
So the problem may be in the encoding or in decoding of file, not in the play audio code. I checked for the same and there were some extra characters embedded while encoding.
We worked on encoding and resolved the issue.
Hope this helps.
NSData *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"FileName.mp3"]
NSURL *url = [[NSURL alloc] initFileURLWithPath: path];
AVAudioPlayer *sound = [[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err] autorelease];
if (! sound) {
NSLog(#"Sound had error %#", [err localizedDescription]);
} else {
[sound prepareToPlay];
[sound play];
}