How to play sound in iOS?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 11:35:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!