Reputation: 1401
i made a simple app where i can record myself and then sample what i've recorded. Since i like spamming buttons, i tried it with my own app. The result was, about 20 the same sounds of myself talking overlapping and creating a horrible mess. How can i prevent such thing in the future?
That's my code:
.h
-(IBAction)record {
TempRecFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithString:@"VoiceFile"]]];
recorder = [[AVAudioRecorder alloc] initWithURL:TempRecFile settings:nil error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
}
-(IBAction)playback {
[recorder stop];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:TempRecFile error:nil];
player.volume = 1;
[player play];
}
Later on i want to play multiple sounds attached to multiple buttons and if all of those start overlapping, the users ears would probably start bleeding very shortly... :(
The problem with multiple sound buttons would be: I would need to restrict every sound to overlapping only with itself. How can I do such thing?
Upvotes: 1
Views: 840
Reputation: 3012
In your Playback method, disable the button first thing. When you init your class, set your class to be the delegate for the AVAudioPlayer and implement the protocol AVAudioPlayerDelegate, specifically you want to catch the audioPlayerDidFinishPlaying:successfully: event. In the event, re-enable the button.
So, this will disable the button, play the sound, and when the sound is done playing enable the button.
Now, for multiple buttons, just do the same thing for each. The catch is you'll need to keep track of an AVAudioPlayer for each button and know which player goes with which button. An NSDictionary could be used to keep the list of players, along with key values.
EDIT: To stop previous playback and start over at the beginning...
Declare an AVPlayer at the class level rather than create a new one for each button press. When the button is pressed you can send it a seekToTime message to start over at the beginning. For multiple buttons have multiple class level AVPlayers.
Edit: If you use AVAudioPlayer class you could do the same thing setting the currentTime property.
Upvotes: 3