Load music files on my iphone application
Hello all this is my first post here i have been working in an iphone application it sound like a small music instrument i've used this code to load my music notes :
// get the path of the sound file
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"do"
ofType:@"mp3"];
// create a URL with the given path
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundPath];
// initialize the AVAudioPlayer with the sound file
btn_do = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:nil];
[fileURL release];
and so on for all other notes (re,me,fa,sol,la,ci)
my question : is this method right because i have to write this code almost 16 times is there 开发者_如何学JAVAany better or stay like I am. Thanks
In essence the code is right. If you want to set up multiple notes, the easiest way to make this more efficient is to create a method you can run for each note. So, create a new method that takes a string and returns a new AVAudioPlayer item:
- (AVAudioPlayer *)getNoteFromFilename:(NSString *)name {
NSString *soundPath = [[NSBundle mainBundle] pathForResource:name
ofType:@"mp3"];
NSURL *fileURL = [NSURL fileURLWithPath:soundPath];
AVAudioPlayer *note = [[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:nil] autorelease];
return note;
}
(Note I have swapped the NSURL method for a convenience, autorelease one which removes the need to separately release it. We are also returning an autoreleased object note
, as per convention)
You can then call this method, as follows:
btn_do = [self getNoteFromFilename:@"do"];
btn_re = [self getNoteFromFilename:@"re"];
and so on!...
Edit: next challenge - try sticking them in an array and so you just have one variable to look after! You could make the index in the array correspond to the 'tag' property of each different button that calls a note...
Give the notes systematic names and write a loop for this. Maybe you can do this with a list.
精彩评论