1

ボタンを押したときに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

4 に答える 4

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ます。

于 2013-09-20T12:15:41.420 に答える
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;

}

音楽ファイルがプロジェクトに正しく追加されていることを確認してください

于 2013-09-20T11:54:54.017 に答える
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 のデリゲートを設定していることを確認してください。

于 2013-09-20T11:37:24.373 に答える