Objective C - IOS - Xcode 4.6.2 - 听不到来自mp3文件的声音

时间:2013-09-20 11:32:56

标签: ios objective-c xcode4.6

我正在关注如何在按下按钮时播放mp3声音的教程。

我创建了一个按钮(playSound)。

我将它添加到视图控制器界面:

- (IBACTION)playSound:(id)sender;

在实现中我声明了所需的头文件,我写了以下内容:

#import "AudioToolbox/AudioToolbox.h"
#import "AVFoundation/AVfoundation.h"

- (IBAction)playSound:(id)sender {

    //NSLog(@"this button works");
    AVAudioPlayer *audioPlayer;
    NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"audio" ofType:@"mp3"];
    //NSLog(@"%@", audioPath);
    NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
    //NSLog(@"%@", audioURL);
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
    [audioPlayer play];

}

我没有收到任何错误。 NSlogs正在记录URL,现在我不知道在哪里可以进一步查看。我还检查了我的MP3声音是否可能已损坏,但事实并非如此。我听到的只是一点点噼啪声,持续1秒钟。然后停止了。

4 个答案:

答案 0 :(得分:4)

您声明了一个局部变量audioPlayer来保存指向播放器的指针。一旦你的按钮处理程序返回,播放器就会在它有机会播放你的声音文件之前被释放。声明一个属性并使用它而不是局部变量。

在YourViewController.m文件中

@interface YourViewController ()
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@end

或在YourViewController.h文件中

@interface YourViewController : UIViewController
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@end

然后在代码中将audioPlayer替换为self.audioPlayer

答案 1 :(得分:0)

<强>被修改

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Name of your audio file" 
                                                              ofType:@"type of your audio file example: mp3"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
    audioPlayer.numberOfLoops = -1;
    audioPlayer.delegate=self;
    [audioPlayer play];

试试这个并告诉我。 确保为audioPlayer设置委托。

答案 2 :(得分:0)

试试这个为我工作

in .h

AVAudioPlayer * _backgroundMusicPlayer;

in .m

NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@"Theme" ofType:@"mp3"];
    NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
    NSError *error;
    _backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
    [_backgroundMusicPlayer setDelegate:self];  // We need this so we can restart after interruptions
    [_backgroundMusicPlayer setNumberOfLoops:-1];
    [_backgroundMusicPlayer play];

答案 3 :(得分:0)

首先在项目中重新添加音乐文件,然后尝试使用此代码 使用日志,您可以看到错误。

NSError *error;

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"bg_sound" ofType:@"mp3"]];

AVAudioPlayer   *audioPlayer = [[AVAudioPlayer alloc]
                              initWithContentsOfURL:url
                              error:&error];
if (error){
//Print Error
NSLog(@"Error in audioPlayer: %@",
          [error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer setNumberOfLoops: -1];
[audioPlayer play];
audioPlayer.volume=1.0;

}

确保您的音乐文件已正确添加到项目中