【问题标题】:iPhone not playing mp3 sound using type=@"mp3"iPhone 不使用 type=@"mp3" 播放 mp3 声音
【发布时间】:2011-01-07 20:26:42
【问题描述】:

我正在编写一个 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);

【问题讨论】:

    标签: iphone objective-c xcode


    【解决方案1】:

    系统声音必须是未压缩的。我遇到了这个并将我的代码更改为使用 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]; 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 2021-11-05
      • 2016-05-29
      • 1970-01-01
      相关资源
      最近更新 更多