Hi everyone I am working on an application which records the user sound and save that to NSDocumentDirectory.The data files are saving well.But the problem is that i want to play those files.I am using the table view for this to populate it with the number of files in the NSDocumentDirectory.But the table shows only one cell the current sound file.I am doing mistake somewhere please help me out.
I am using this code to play.
-(void)PlayAudio
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"strffdsa %#",documentsDirectory);
NSURL *fileURL = [NSURL fileURLWithPath:recorderFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
player.numberOfLoops = 0;
//[fileURL release];
[player play];
[player setDelegate: self];
}
Where recorderFilePath is the path of file.The path is new everytime with the help of NSDate frmattor.But not getting how to populate the table view with all the files residing in the DocumentDirectory.
Please-2 help me...I am new to this technology.
Thanks in advance to all ........
Use an enumerator to simplify iterating through the Documents directory to search for music files.
//Use an enumerator to store all the valid music file paths at the top level of your App's Documents directory
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
for (NSString *path in directoryEnumerator)
{
//check for all music file formats you need to play
if ([[path pathExtension] isEqualToString:#"mp3"] || [[path pathExtension] isEqualToString:#"aiff"] )
{
[myMusicFiles addObject:path];
}
}
//the NSArray 'myMusicFiles' will be the datasource for your tableview
You need NSFileManager's contentsOfDirectoryAtPath:error: method to get an array of files in the request directory. Then iterate over that array to find the file name you're looking for.
Related
In my application I want to implement a simple Alarm function. I know how to use UILocalNotifications, but I came across this source code with a like UI of the iPhone's native Clock app alarm area as well as it having a believe a type of data persistence. Two things I am not good at interface design and data persistence this source code has. But I downloaded it and started playing around with it to find the alarms are not persistent.
Download
Does anyone know how the source code can be adjusted so that it is persistent and the plist can be saved and read to and from? I am open to learning too, this area is somewhat unknown to me too. Thanks
I review your code and find issue that you not moved your "Alarms.plist" file form resource to document directory. we are not able to edit file which is in resource folder. so write following code in app delegate file.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *theFileName = #"Alarms.plist"; //Change this appropriately
NSString *oldPath = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];//[NSString stringWithFormat:#"%#/Inbox/%#", documentsDirectory, theFileName];
NSString *newPath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, theFileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:newPath])
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
Perform save operation on file which is in Document directory folder.
try this code... to save plist from bundle to Document Directory
Notice that you will have "Unable to read... " just at the first app launch
- (NSMutableArray *)displayedObjects
{
if (_displayedObjects == nil)
{
NSString *path = [[self class] pathForDocumentWithName:#"Alarms.plist"];
NSArray *alarmDicts = [NSMutableArray arrayWithContentsOfFile:path];
if (alarmDicts == nil)
{
NSLog(#"Unable to read plist file: %#", path);
NSLog(#"copy Alarms.plist to: %#", path);
NSString *pathToSetingbundle = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];
[[NSFileManager defaultManager]copyItemAtPath:pathToSetingbundle toPath:path error:nil];
}
_displayedObjects = [[NSMutableArray alloc]
initWithCapacity:[alarmDicts count]];
for (NSDictionary *currDict in alarmDicts)
{
Alarm *alarm = [[Alarm alloc] initWithDictionary:currDict];
[_displayedObjects addObject:alarm];
NSLog(#"#disply obj %#", alarm);
}
}
return _displayedObjects;
}
I'm working on an iPhone app and I need to add a new key-value pair to an existing plist file using objective-c. This is what I've tried so far:
NSString *myFile=[[NSBundle mainBundle] pathForResource:#"Favourites" ofType:#"plist"];
dict = [[NSMutableDictionary alloc] initWithContentsOfFile:myFile];
[dict setObject:textContent forKey:keyName];
[dict writeToFile:myFile atomically:YES];
However, when I do this it doesn't write it to the file. I've only seen resources based on either changing the value of a key or adding to another key. Is there another way to accomplish this?
Thank you for your time
You cannot make any changes in the bundle. So what you have to do is copy the .plist file into your documents directory and do the manipulation there.
Something along these lines:
//check for plist
//Get documents directory's location
NSArray*docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*filePath=[docDir objectAtIndex:0];
NSString*plistPath=[filePath stringByAppendingPathComponent:#"Favourites.plist"];
//Check plist's existance using FileManager
NSError*err=nil;
NSFileManager*fManager=[NSFileManager defaultManager];
if(![fManager fileExistsAtPath:plistPath])
{
//file doesn't exist, copy file from bundle to documents directory
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:#"Favourites" ofType:#"plist"];
[fManager copyItemAtPath:bundlePath toPath:plistPath error:&err];
}
//Get the dictionary from the plist's path
NSMutableDictionary*plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//Manipulate the dictionary
[plistDict setObject:textContent forKey:keyName];
//Again save in doc directory.
[plistDict writeToFile:myFile atomically:YES];
In my app I imported 4 sound files. Now I want to list all the sound files in a View. When the user clicks any one of the sound, it needs to be selected and played as like in the Alarms app (choosing the sound for alarm). The difference here is I am getting the sound from my project. I have searched in SO and Google but I couldn't find a solution exactly for this problem.
Assuming that "In my app i imported 4 sound files" means that the files are in your app bundle (and also assuming that the extension of the files is MP3 - you can change it to whatever extensions they actually have):
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
NSFileManager *mgr = [[NSFileManager alloc] init];
NSArray *allFiles = [mgr contentsOfDirectoryAtPath:bundlePat error:NULL];
for (NSString *fileName in allFiles)
{
if ([[fileName pathExtension] isEqualToString:#"mp3"])
{
NSString *fullFilePath = [bundlePath stringByAppendingPathComponent:fileName];
// fullFilePath now contains the path to your MP3 file
DoSomethingWithFile(fullFilePath);
}
}
I have a view responsible for recording audio. How can i record several audios and show them in a table view?
I'm trying to use docs directory to save the recorded audios:
NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsFolder = [folders objectAtIndex:0];
NSString *recordedAudio = [documentsFolder stringByAppendingPathComponent:newAudio];
newAudio is a string that contains new audio name typed by the user with the suffix .m4a.
To retrieve the saved audios i'm trying something like this:
NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsFolder = [folders objectAtIndex:0];
NSArray *folderContents = [[NSArray alloc] initWithContentsOfFile:documentsFolder];
I expected folderContents would have all the audios stored at documentsFolder so a could load my table, but its count is 0. I'm new in docs directory, probably i'm missing something, or doing all wrong.
What is wrong, or there is another way to accomplish that?
You are getting the contents of the documents directory incorrectly. This is the right way:
NSArray *folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsFolder error:nil];
Documents is not a file, it is a folder.
edit: This is how you save a file
Assuming you have an NSData object such as
NSData *audioData = ...; // initialiazed with your recording
After you create your recordedAudio string, which is actually just the filename you want to write to (should probably called audioPath or something), you need to add this:
[audioData writeToFile:recordedAudio atomically:YES];
I am new to iphone.I am working on audio player here i am struck in the middle because i am facing some issue that is here in my project i have 2 directories in resource folder.In each directory i have 6mp3 audio files.So my issue is when user gives the path to the 3rd mp3 song in first directory in resources folder from that we have to play continuous all the songs like 4th,5th,6th mp3files also which is placed in that directory in resources folder.here is my code for this
NSString *chapterString =#"3";
NSString *string = [[NSBundle mainBundle]pathForResource:chapterString ofType:#"mp3" inDirectory:#"raj"];
NSLog(#"string is %#",string);
url = [NSURL fileURLWithPath:string isDirectory:YES];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
If any body know this please help me..
Put all the songs in an array
Initialize a global variable suppose x
Write the following AVAudioPlayer Delegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
if (x<([_downloadedSongArray count]-1))
{
x=x+1;
[self loadSong];
}
}
- (void)loadSong
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
_audioDocumentsDirectory = [paths objectAtIndex:0];
_audioDocumentsDirectory = [_audioDocumentsDirectory stringByAppendingPathComponent:#"Songs"];
NSString *selectedSong = [_downloadedSongArray objectAtIndex:x];
_sharerDownloadedString=selectedSong;
selectedSong = [selectedSong stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
_audioDocumentsDirectory = [_audioDocumentsDirectory stringByAppendingPathComponent:selectedSong];
url = [NSURL fileURLWithPath:_audioDocumentsDirectory];
[_audio stop];
_audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[_audio prepareToPlay];
[_audio play];
[Utility setPlaying:YES];
[_audio setDelegate:self];
}
Where _downloadedSongArray is an array where all song are. And loadSong is a method which load next/prev song from an array based on index and assign to the AVAudioPlayer.
You could get the contents of the directories into an Array via NSFileManager, upon finishing song x..play the next song in the array, song y.