在iPhone/iPad应用程序中播放音频文件?

问题描述:

我想在我的应用程序中播放声音,我正在使用.mp3文件类型。它在模拟器中工作正常,但是当我将它发送到我的设备时,它不工作并且没有产生任何声音,任何人都无法帮助我为什么它不能在设备上工作或哪种文件格式更适合在iPhone和iPad中播放音频文件?在iPhone/iPad应用程序中播放音频文件?

NSURL *tapSound = [[NSBundle mainBundle] URLForResource: [NSString stringWithFormat:@"%@",SoundFileName] withExtension: @""]; 

// Store the URL as a CFURLRef instance 
self.soundFileURLRef = (CFURLRef) [tapSound retain]; 

// Create a system sound object representing the sound file. 
AudioServicesCreateSystemSoundID (
        soundFileURLRef, 
        &soundFileObject 
        ); 

AudioServicesPlaySystemSound (soundFileObject); 

以上是我的代码来播放声音

谢谢。

+0

@ user532445,或者如果没有人发布可接受的答案,则将答案发布到您自己的问题中,以便您在开发过程中继续前进。这样你就回到了SO。 – 2011-04-16 13:40:46

如果设备静音,系统声音ID将不会播放,所以这可能是原因。 (它们只是用于用户界面效果的目的,如警报等,按照official documentation。)

因此,我会试图使用AVAudioPlayer风格的方法。作为示例(无双关语)实现:

// *** In your interface... *** 
#import <AVFoundation/AVFoundation.h> 

... 

AVAudioPlayer *testAudioPlayer; 

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

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

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

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



// *** In your dealloc... *** 
[testAudioPlayer release]; 

您还应该记得设置适当的音频类别。 (请参阅AVAudioSessionsetCategory:error:方法。)

最后,您需要将AVFoundation库添加到您的项目中。为此,请在Xcode的Groups & Files列中单击您的项目目标,然后选择“Get Info”。然后选择常规选项卡,单击底部“链接库”窗格中的+并选择“AVFoundation.framework”。

我诚实地建议使用AVAudioPlayer代替这个,但你可以尝试使用这个替代代码。在你的例子中,它看起来像忘了包含扩展名,这也可能是问题。模拟器在命名上更加宽松,所以如果您忘记了扩展名,它可能会在模拟器上播放,而不是设备。

SystemSoundID soundFileObject; 
CFURLRef soundFileURLRef = CFBundleCopyResourceURL (CFBundleGetMainBundle(),CFSTR ("sound"),CFSTR ("mp3"),NULL); 
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject); 
AudioServicesPlaySystemSound (soundFileObject);