2014-11-09 93 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的評論中所說的,聲音播放在模擬器中失敗。嘗試播放視頻時遇到此問題。

有趣的部分是聲音播放照片應用程序中相同的視頻很好。