2012-12-09 54 views
2

我試圖在我的iPhone應用程序中播放短暫的鬧鐘聲音 我使用了我發現的這段代碼,但它不會播放任何聲音。IOS播放短音

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

THX

+1

嘗試在設備上,忘記模擬器 – 2012-12-09 14:58:00

回答

3

使用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]; 
1

創建聲音時,您沒有正確處理Sound變量。相反,您正在使用camerSound。使用正確的參數調用AudioServicesPlayAlertSound應該可以工作。

1

這對我來說非常適合。

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