如何在iOS中播放声音? [英] How to play sound in iOS?

查看:211
本文介绍了如何在iOS中播放声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在stackoverflow上找到了这么多解决方案,但由于某些原因,所有这些解决方案都无法产生任何声音。

I have found so many solutions here on stackoverflow, but for some reason all of them failed to produce any sound what so ever.

这是我当前的代码:

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);
}

这个解决方案直接出书。但是当我运行项目时,如果没有产生任何声音。我的文件是test.aif,这是5秒长。

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.

任何建议为什么它不起作用?如果这不是最好的解决方案,你如何在iOS6上产生声音?

Any suggestions why it's not working? If that's not the best solution, how do you produce a sound on iOS6?

推荐答案

根据这个话题和其他人,播放音频剪辑可以像下面一样简单,我使用的方法(功能) )。我自己做过。

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);
    }
}

这篇关于如何在iOS中播放声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆