2014-11-09 94 views
1

我试图单击按钮时播放声音。首先,我进口AudioToolbox在头文件,然后添加代码到火灾时,按下按钮,像这样的IBAction为:简单播放iOS中的声音

- (void)viewDidLoad { 
    [super viewDidLoad]; 
} 
- (IBAction)button1:(id)sender { 
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"mySong" ofType:@"wav"]; 
    SystemSoundID soundID; 
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundPath], &soundID); 
    AudioServicesPlaySystemSound (soundID); 
} 

我甚至在方法抛出的NSLog以确保它的射击。它是。我也是,但在字符串中的一条路上看它是否会崩溃,它的确如此。我确信我将短音响文件拖放到应用程序中。测试我的扬声器,通过在模拟器上的YouTube上测试设备模拟器上的音频。我无法弄清楚我做错了什么。

当我改变了代码,以这样的:

- (IBAction)button1:(id)sender { 


    AVAudioPlayer *testAudioPlayer; 

    // *** Implementation... *** 

    // Load the audio data 
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"]; 
    NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath]; 
    NSError *audioError = nil; 

    // Set up the audio player 
    testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError]; 


    if(audioError != nil) { 
     NSLog(@"An audio error occurred: \"%@\"", audioError); 
    } 
    else { 
     [testAudioPlayer setNumberOfLoops: -1]; 
     [testAudioPlayer play]; 
    }} 

我得到的错误:警告:137:错误尝试设置(空)音频设备的采样率

+1

尝试在设备上而不是在模拟器中进行测试。 – matt 2014-11-09 04:52:57

回答

1

嗨'逸!根据你的问题,你可以请检查你的音频文件是否出现在你的项目文件夹中。可能会发生这种情况,你忘记勾选“复制项目,如果需要”,所以它可能不在你的项目文件中。

您还可以播放设备中提供的声音。访问下面的链接会有帮助。

https://github.com/TUNER88/iOSSystemSoundsLibrary

我测试你的代码,它工作正常,并没有得到坠毁。这就是我所做的。 enter image description here

+0

是的,它出现在我的项目文件中。 – John 2014-11-09 04:40:30

+0

您也可以从链接中尝试演示,以解决您的问题。我已经添加了我所做的事情的形象,它给了我正确的道路,不会崩溃。 – 2014-11-09 05:20:30

1

正如在@ matt的评论中所说的,声音播放在模拟器中失败。尝试播放视频时遇到此问题。

有趣的部分是声音播放照片应用程序中相同的视频很好。