问题
I have found so many solutions here on stackoverflow, but for some reason all of them failed to produce any sound what so ever.
Here is my current code:
PRE: I've added AudioToolbox.framework and imported <AVFoundation/AVFoundation.h> in my .m file
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL* sndurl = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"aif"];
SystemSoundID snd;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)sndurl, &snd);
AudioServicesAddSystemSoundCompletion(snd, nil, nil, SoundFinished, nil);
AudioServicesPlaySystemSound(snd);
}
void SoundFinished (SystemSoundID snd, void* context) {
AudioServicesRemoveSystemSoundCompletion(snd);
AudioServicesDisposeSystemSoundID(snd);
}
This solution is straight out of book. But when I run the project, if fails to produce any sound. My file is test.aif, which is 5 seconds long.
Any suggestions why it's not working? If that's not the best solution, how do you produce a sound on iOS6?
回答1:
According to this topic and others, playing an audio clip can be as simple as the following, my using a method (function). I've done it before myself.
- (void)playAudio {
[self playSound:@"pageflip1" :@"wav"];
}
- (void)playSound :(NSString *)fName :(NSString *) ext{
SystemSoundID audioEffect;
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);
}
}
回答2:
Make sure to try testing it on an actual device because the simulator can have problems when using AVFoundation.
来源:https://stackoverflow.com/questions/16450274/how-to-play-sound-in-ios