IOS 播放短音



我正在尝试在我的iPhone应用程序中播放简短的闹钟声音我正在使用我找到的这段代码,但它不会播放任何声音。

NSString *toneFilename = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"wav"];
    NSURL *toneURLRef = [NSURL fileURLWithPath:toneFilename];
    SystemSoundID Sound;
    AudioServicesCreateSystemSoundID(
                                     (__bridge CFURLRef) toneURLRef,
                                     &camerSound
                                     );
    AudioServicesPlaySystemSound(Sound);

当我尝试振动时,它可以工作:

AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

感谢

Using AVFoundationFramework

AVFoundation.framework添加到项目中。

#import <AVFoundation/AVFoundation.h>
NSString *toneFilename = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"wav"];
NSURL *toneURLRef = [NSURL fileURLWithPath:toneFilename];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL: toneURLRef error: nil];
player.currentTime = 0;
player.volume = 1.0f;
[player play];

创建声音时,您没有正确处理Sound变量。相反,您使用的是camerSound .使用正确的参数调用AudioServicesPlayAlertSound应该有效。

这对我来说非常有效。

将 AVFoundation 和 AudioToolBox 框架添加到项目中

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
@interface TestViewController : UIViewController
{
    SystemSoundID SoundID;
}
@implementation TestViewController
-(void) viewDidLoad {
    [super viewDidLoad];
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"caf"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &SoundID);  //When using ARC, make sure to use __bridge
 }
-(void) playSound {
     AudioServicesPlaySystemSound(SoundID);
 }

最新更新