2010-11-18 62 views
4

我有一個應用程序,我正在使用它,它使用一些硬件傳感器在屏幕上提供數據,還有一個標籤用數字更新。當數字超過100或某物時,我想要播放聲音。例如,說它正在讀數字,然後突然它找到一個好點(或其他),然後我想要一個聲音播放或點亮一個燈。我是一個絕對的初學者,如果答案對於絕對的初學者來說是很容易理解的,那將會很好。如何在目標C iphone編碼中播放聲音

回答

10

我使用的系統AudioToolbox.framework在我簡單的玩遊戲的聲音。我加入這個靜態函數共同MyGame類:

+ (SystemSoundID) createSoundID: (NSString*)name 
{ 
    NSString *path = [NSString stringWithFormat: @"%@/%@", 
        [[NSBundle mainBundle] resourcePath], name]; 


    NSURL* filePath = [NSURL fileURLWithPath: path isDirectory: NO]; 
    SystemSoundID soundID; 
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID); 
    return soundID; 
} 

我添加了「Morse.aiff」文件,項目資源和(任何)類的初始化有以下初始化它:

self.mySound = [MyGame createSoundID: @"Morse.aiff"]; 

而且然後我用此呼叫播放聲音:

AudioServicesPlaySystemSound(mySound); 

此外,不要忘記導入AudioServices.h文件。

此音頻工具箱還可以播放不同的聲音格式。

+0

請記住,您將需要調用AudioServicesDisposeSystemSoundID以避免內存泄漏! (因爲SystemSoundID來自較低級別的框架) – 2013-05-14 08:41:47

1

查看AVAudioPlayer類的文檔。它可以讓你播放聲音剪輯。如果你遇到麻煩,給我們看一些代碼。

+0

好,謝謝,我會看看那個,showi ng將是下一個,我知道這很愚蠢,但你想具體做什麼? – DanielsCaleb0 2010-11-18 14:41:17

1

如果聲音長達5秒鐘,並且不需要立體聲輸出,我建議您使用系統聲音來做到這一點。這是任何其他方法的簡單和更好的解決方案。在名稱提供 蘋果的示例代碼SysSound

EDIT1 或許教程可以幫助你更 http://howtomakeiphoneapps.com/2009/08/how-to-play-a-short-sound-in-iphone-code/

+0

這是偉大的,def。幫助。任何想法如何使它在超過一定數量時工作? – DanielsCaleb0 2010-11-18 15:25:38

+1

沒有看到任何代碼,它不容易說如何,但讓我們猜你的數字是整數,應該在你的代碼if-statement將會比較值(將它放在你賦值的地方),然後就在if語句下把你的系統聲音,它會發揮 – Vanya 2010-11-18 15:38:47

+0

這解釋了不同的球員和何時使用它們:http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/MultimediaPG/UsingAudio/UsingAudio。html – griotspeak 2010-11-18 22:24:39

4

^h

#import <AVFoundation/AVFoundation.h> 

@interface CMAVSound : NSObject { 
    AVAudioPlayer *audioPlayer; 
} 

- (id)initWithPath:(NSString*)fileNameWithExctension; 
- (void)play; 

@end 

#import "CMAVSound.h" 

@implementation CMAVSound 

-(void)dealloc { 
    [audioPlayer release]; 
} 

- (id)initWithPath:(NSString*)fileNameWithExctension { 
    if ((self = [super init])) { 
     NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], fileNameWithExctension]]; 

     NSError *error; 
     audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 

     if (audioPlayer == nil) { 
      NSLog(@"%@", [error description]); 
     } 
    } 
    return self; 
} 

- (void)play { 
    [audioPlayer play]; 
} 

@end