How to play sound in iOS?

2019-05-11 20:04发布

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?

2条回答
混吃等死
2楼-- · 2019-05-11 21:02

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);
    }
}
查看更多
Luminary・发光体
3楼-- · 2019-05-11 21:02

Make sure to try testing it on an actual device because the simulator can have problems when using AVFoundation.

查看更多
登录 后发表回答