2012-09-26 111 views
-1

我將我的項目轉換爲ARC。 Xcode的代碼改變了這一行的例子不要播放聲音

soundFileURLRef = (CFURLRef) [tapSound retain]; 

soundFileURLRef = (__bridge CFURLRef) tapSound; 

,但沒有播放聲音。怎麼了?

- (IBAction)buttonTapped:(UIButton *)sender { 
     // Create the URL for the source audio file. The URLForResource:withExtension: method is new in iOS 4.0 
     NSURL *tapSound = [[NSBundle mainBundle] URLForResource: @"abide" withExtension: @"aif"]; 

     CFURLRef  soundFileURLRef; 
     SystemSoundID soundFileObject; 

     // Store the URL as a CFURLRef instance 
     soundFileURLRef = (__bridge CFURLRef) tapSound; // I think this line is wrong 

     // Create a system sound object representing the sound file. 
     AudioServicesCreateSystemSoundID (

              soundFileURLRef, 
              &soundFileObject 
             ); 

     AudioServicesPlaySystemSound (soundFileObject); 
    } 

回答

3

從邏輯上說,你的代碼看起來完全沒問題。我懷疑你實際上沒有將abide.aif與你的應用程序捆綁在一起,或者你錯誤地輸入了錯誤的名稱(可能是aiff?)。您可以通過在[NSBundle URLForResource:withExtension:]調用之後放置一個斷點並檢查tapSound的內容來驗證此情況。

確保您實際上已經包括它的目標,在「複製包資源」:

此外,你應該知道,調用AudioServicesCreateSystemSoundID應該用AudioServicesDisposeSystemSoundID調用來平衡。你在這裏不必要地分配內存,ARC不會爲你處理這個問題。

做到這將是完成所有的工作,以創建一個在您awakeFromNibviewDidLoad方法SystemSoundID,它存儲爲一個實例變量,只有撥打您的按鈕點擊方法AudioServicesPlaySystemSound理想的方式。在你的dealloc方法中,你應該調用AudioServicesDisposeSystemSoundID

讓我知道它是怎麼回事。

+0

我相信你的意思是說「只需在你的按鈕點擊方法中調用AudioServicesPlaySystemSound()」。不錯的寫作。 – NJones

+0

@NJones:哎呀!感謝您的發現。 –