如何在Xcode中的iOS 5中播放随机声音?
我不断收到“引发异常”错误。

我尝试了这个:

int randomNumber = arc4random() % 24 + 1;

NSString *tmpFileNameRandom = [[NSString alloc] initWithFormat:@"Sound%d", randomNumber];

NSString *fileName = [[NSBundle mainBundle] pathForResource:tmpFileNameRandom ofType:@"mp3"];

AVAudioPlayer * soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileName] error:nil];

[soundPlayer prepareToPlay];
[soundPlayer play];

谢谢!

最佳答案

首先,将您的ViewController.h更改为

#import <UIKit/UIKit.h>

@class AVAudioPlayer;

@interface ViewController : UIViewController

-(IBAction)PlayRandomSound;
@property (nonatomic, retain) AVAudioPlayer *soundPlayer;


@end

和ViewController.m的第一行
#import "ViewController.h"

#import <AVFoundation/AVAudioPlayer.h>


@implementation ViewController

@synthesize soundPlayer = _soundPlayer;


-(IBAction)PlayRandomSound{

    int randomNumber = arc4random() % 8 + 1;

    NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"Sound%02d", randomNumber] ofType:@"mp3"]];


    _soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];

    [_soundPlayer prepareToPlay];
    [_soundPlayer play];


    NSLog(@"randomNumber is %d", randomNumber);
    NSLog(@"tmpFilename is %@", soundURL);
}

编辑:我只是后来才注意到您不使用ARC,所以此代码有少量泄漏。但是,它将为开始做。也许在创建ViewController时应将_soundPlayer设置为nil,然后再检查:如果不是nil:释放它并创建一个新的,否则只需创建一个新的即可。或者,如果这是一个新项目,则可以考虑切换到ARC。

关于objective-c - 播放随机声音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8975266/

10-11 08:57