iPhone 无法使用 type= @"mp3"播放 mp3 声音

标签 iphone objective-c xcode

我正在编写一个 iPhone 应用程序,当发生特定事件时,会播放声音。我尝试使用不同的 WAV、MP3、M4A 文件,但遇到间歇性问题。下面的代码在模拟器中运行良好,但 MP3 无法在 iPhone 上播放。 (如果有的话,3GS)。有任何想法吗?我已将 mp3 文件更改为 wav 文件,它将适用于下面提供的文件 (knock_knock),但不适用于其他文件。可能是它的编码方式?

感谢任何帮助。谢谢

这是代码:

SystemSoundID soundID;
NSString *soundFile;

if (something == somethingelse) {
    soundFile = [[NSBundle mainBundle] pathForResource:@"knock_knock" ofType:@"wav"];
}
else {
   soundFile = [[NSBundle mainBundle] pathForResource:@"strike" ofType:@"mp3"];
}
   AudioServicesCreateSystemSoundID((CFURLRef)
                                 [NSURL fileURLWithPath:soundFile]
                                 , &soundID);
AudioServicesPlaySystemSound(soundID);

最佳答案

系统声音必须未压缩。我遇到了这个问题并更改了代码以使用 AVAudioSession 和 AVAudioPlayer。在我的脑海中,类似这样的东西(需要更好的错误检查)

    -(void)load {
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [self path]];
    if (fileURL) {

        AVAudioPlayer *newPlayer =
        [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                               error: nil];
        [fileURL release];
        [self stop];
        self.player = newPlayer;
        [newPlayer release];

        [self.player prepareToPlay];
    }   
}

    -(void)play {

    if (self.player == nil)
        [self load];

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory: AVAudioSessionCategoryAmbient error:&err];
    if(err){
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];

    self.player.currentTime = 0;
    [self.player play]; 
}

关于iPhone 无法使用 type= @"mp3"播放 mp3 声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2111293/

相关文章:

objective-c - 数据库错误 : use of undeclared identifier

c++ - ffmpeg armv7s 编译段错误

objective-c - 混合使用 Objective-C、C++ 和 OpenCV

iphone - 包含 1000 多张图片的 iPad Catalog 应用程序

iphone - 当 View 的类为 TPKeyboardAvoidingScrollView 时,UIButton 不会在模拟器上显示

iphone - 无需松开手指即可从一个按钮滑动到另一个按钮

iphone - UINavigationBar 标题标签文字

iphone - Objective C - 类别中的静态变量

objective-c - 如何播放多个音频文件?

ios - UINavigationController 对底下的 UITableView 透明