AVAudioPlayer iOS没声音

时间:2015-01-30 08:52:33

标签: objective-c

似乎问了类似的问题,但似乎没有一个解决方案适合我。不能为我的生活理解为什么我的代码不起作用所以在这里。 我没有得到任何错误但也没有声音。

@interface MainApp ()

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
-(void)playSoundFX:(NSString*) soundFile;

@end

@implementation MainApp

- (void)viewDidLoad {
    [super viewDidLoad];

    // Play sound
    [self playSoundFX:@“sound.mp3"];
}

// Play sound
- (void)playSoundFX:(NSString*)soundFile {

    // Setting up path to file url
    NSBundle* bundle = [NSBundle mainBundle];
    NSString* bundleDirectory = (NSString*)[bundle bundlePath];
    NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:soundFile]];

    // Make an audioPlayer object and play file
    NSError *error;
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    [audioPlayer setVolume:100.0f];

    if (audioPlayer == nil)
        NSLog(@"%@", [error description]);
    else
        [audioPlayer play];
}

@end

*********vvvvvvvvv Amended Code that works vvvvvvvvv**********

@interface MainApp ()

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
-(void)playSoundFX:(NSString*) soundFile;

@end

@implementation MainApp

- (void)viewDidLoad {
    [super viewDidLoad];

    // Play sound
    [self playSoundFX:@“sound.mp3"];
}

// Play sound
- (void)playSoundFX:(NSString*)soundFile {

    // Setting up path to file url
    NSBundle* bundle = [NSBundle mainBundle];
    NSString* bundleDirectory = (NSString*)[bundle bundlePath];
    NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:soundFile]];

    // Make an audioPlayer object and play file
    NSError *error;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    [self.audioPlayer setVolume:100.0f];

    if (self.audioPlayer == nil)
        NSLog(@"%@", [error description]);
    else
        [self.audioPlayer play];
}

@end

2 个答案:

答案 0 :(得分:0)

我在iPhone上执行你的代码。它工作正常。请选择一个设备并运行您的代码。我希望它能用声音正确执行。

答案 1 :(得分:0)

你必须将功能分开..

在viewDidLoad中加载音频文件并在播放动作中播放,有点像这样

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
{
    AVAudioPlayer *_audioPlayer;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Construct URL to sound file
    NSString *path = [NSString stringWithFormat:@"%@/sound.mp3", [[NSBundle mainBundle] resourcePath]];
    NSURL *soundUrl = [NSURL fileURLWithPath:path];

    // Create audio player object and initialize with URL to sound
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)playSoundTapped:(id)sender
{
    // When button is tapped, play sound
    [_audioPlayer play];
}