0

(AVFoundation.framework を使用)

#import "AVFoundation/AVFoundation.h"

問題が発生したので、クラスの init メソッドで最初にこのコードを試しました (これが最初にロードされるメソッドです)。

NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops=-1;
[player play];

しかし、スレッドで実行することにしたので、うまくいきませんでした: init メソッド:

[NSThread detachNewThreadSelector:@selector(playMusic) toTarget:self withObject:nil];

およびメソッド自体:

-(void) playMusic {
    NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
    NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
    player.numberOfLoops=-1;
    [player play];
}

もちろん *.h ファイルで宣言されています。それもうまくいきませんでした。

オンラインでデバッグしようとしました

}

playMusic メソッドのファイルは 2 ~ 3 秒間再生されてから停止します。デバッグなしでは再生されません。何が問題ですか?

4

1 に答える 1

2

AVAudioPlayer はすぐに割り当て解除されます。プレーヤーを保持する必要があります。したがって、AVAudioPlayer をクラスのインスタンス変数にします。

于 2012-05-01T19:03:55.893 に答える