2011-11-23 9 views
7

tab bar,nav bar and table viewでアプリを作成しました。iOSのコントロールでオーディオを再生する

テーブルビューでは、一部の音声を聞くことができます。

新しいビューが開き、再生、一時停止、音量スライダ、進行状況スライダ、現在の時間のラベルが表示されます。

これは機能しますが、完全ではありません。 私はオーディオを再生することができます、私はオーディオを一時停止することができます、私はまた、前方または後方にスキップするためにスライダを使用することができます。しかし、今:

私はnavbarの[戻る]ボタンを押すと、曲が再生を続けます。それは大丈夫ですが、再びビューに戻ると、タイマーとスライダがリセットされます。私は曲を一時停止することはできません、ちょうどそれが再生を停止utilを待つ必要があります。

また、テーブルビューに戻り、再生する別のファイルを選択すると、最初のファイルの再生が停止しません。ここで

はAudio1DetailViewController.hコードです:ここで

 #import <UIKit/UIKit.h> 
    #import <AVFoundation/AVFoundation.h> 

    @interface Audio1DetailViewController: UIViewController <AVAudioPlayerDelegate> { 

    IBOutlet UISlider *volumeControl; 
    IBOutlet UILabel *timerLabel; 
    IBOutlet UISlider *progressBar; 

    AVAudioPlayer *audioPlayer; 
    NSTimer *playbackTimer; 

    } 

    @property (nonatomic, retain) IBOutlet UISlider *volumeControl; 
    @property (nonatomic, retain) IBOutlet UILabel *timerLabel; 
    @property (nonatomic, retain) IBOutlet UISlider *progressBar; 
    @property (nonatomic, retain) NSTimer *playbackTimer; 
    @property (nonatomic, retain) AVAudioPlayer *audioPlayer; 
    -(IBAction) playAudio; 
    -(IBAction) stopAudio; 
    -(IBAction) adjustVolume; 
    -(IBAction) sliderChanged; 

    @end 

はAudio1DetailViewController.mコードです:ここで

 #import "Audio1DetailViewController.h" 


    @implementation Audio1DetailViewController 

    @synthesize volumeControl, timerLabel, playbackTimer, progressBar, audioPlayer; 

    -(void)playAudio 
    { 
    playbackTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
    target:self 
    selector:@selector(updateTime) 
    userInfo:nil 
    repeats:YES]; 
    [audioPlayer play]; 
    } 
    -(void)stopAudio 
    { 
    [playbackTimer invalidate]; 
    [audioPlayer stop]; 
    } 
    -(void)adjustVolume 
    { 
    if (audioPlayer != nil) 
    { 
    audioPlayer.volume = volumeControl.value; 
    } 
    } 

    -(void)updateTime 
    { 
    float minutes = floor(audioPlayer.currentTime/60); 
    float seconds = audioPlayer.currentTime - (minutes * 60); 

    float duration_minutes = floor(audioPlayer.duration/60); 
    float duration_seconds = 
    audioPlayer.duration - (duration_minutes * 60); 

    NSString *timeInfoString = [[NSString alloc] 
    initWithFormat:@"%0.0f.%0.0f/%0.0f.%0.0f", 
    minutes, seconds, 
    duration_minutes, duration_seconds]; 

    timerLabel.text = timeInfoString; 
    [timeInfoString release]; 
    } 

    - (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
    pathForResource:@"001Fatiha" 
    ofType:@"MP3"]]; 

    NSError *error; 
    audioPlayer = [[AVAudioPlayer alloc] 
    initWithContentsOfURL:url 
    error:&error]; 

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
    [[AVAudioSession sharedInstance] setActive: YES error: nil]; 

    if (error) 
    { 
    NSLog(@"Error in audioPlayer: %@", 
    [error localizedDescription]); 
    } else { 
    audioPlayer.delegate = self; 
    [audioPlayer prepareToPlay]; 
    } 


    playbackTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self 
    selector:@selector(updateSlider) userInfo:nil repeats:YES]; 

    progressBar.maximumValue = audioPlayer.duration; 
    // Set the valueChanged target 
    [progressBar addTarget:self action:@selector(sliderChanged:) forControlEvents: 
    UIControl EventValueChanged]; 
    } 

    - (void)updateSlider { 
    // Update the slider about the music time 
    progressBar.value = audioPlayer.currentTime; 
    } 

    - (IBAction)sliderChanged:(UISlider *)sender { 
    // Fast skip the music when user scroll the UISlider 
    [audioPlayer stop]; 
    [audioPlayer setCurrentTime:progressBar.value]; 
    [audioPlayer prepareToPlay]; 
    [audioPlayer play]; 
    } 

    -(void)audioPlayerDidFinishPlaying: 
    (AVAudioPlayer *)player successfully:(BOOL)flag 
    { 
    } 


    -(void)audioPlayerDecodeErrorDidOccur: 
    (AVAudioPlayer *)player error:(NSError *)error 
    { 
    } 
    -(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player 
    { 
    } 
    -(void)audioPlayerEndInterruption:(AVAudioPlayer *)player 
    { 
    } 

    -(void)viewDidUnload { 
    audioPlayer = nil; 
    volumeControl = nil; 

    } 

    -(void)dealloc { 
    [audioPlayer release]; 
    [volumeControl release]; 
    [playbackTimer release]; 
    [super dealloc]; 
    } 

    @end 

はAudioTableViewController.h

 #import <UIKit/UIKit.h> 

    @class Audio1DetailViewController; 


    @interface AudioTableViewController : UITableViewController 
    <UITableViewDelegate,UITableViewDataSource>{ 


    IBOutlet UITableView *audioTableView; 
    NSMutableArray *audioArray; 
    Audio1DetailViewController *audio1DetailViewController;   
    } 

    @property (nonatomic, retain) NSMutableArray *audioArray; 
    @property (nonatomic, retain) Audio1DetailViewController *audio1DetailViewController; 

    @end 

とAudioTableViewControllerです.m

#import "AudioTableViewController.h" 
    #import "Audio1DetailViewController.h" 

    #import "DEQAppDelegate.h" 

    @implementation AudioTableViewController 
    @synthesize audioArray; 
    @synthesize audio1DetailViewController; 

    - (id)initWithStyle:(UITableViewStyle)style 
    { 
     self = [super initWithStyle:style]; 
     if (self) { 
      // Custom initialization 
    { 
     return self; 
    } 

    - (void)didReceiveMemoryWarning 
    { 
     // Releases the view if it doesn't have a superview. 
     [super didReceiveMemoryWarning]; 

     // Release any cached data, images, etc that aren't in use. 
    } 

    #pragma mark - View lifecycle 

    - (void)viewDidLoad{ 
     [super viewDidLoad]; 
     self.title = NSLocalizedString(@"Audio", @"Audio"); 
     self.audioArray = [[NSArray alloc] initWithObjects: 
          @"1. Het Begin", @"2. De Mensen", //etcetera      
        nil]; 
     // Uncomment the following line to preserve selection between presentations. 
     self.clearsSelectionOnViewWillAppear = NO; 

     // Uncomment the following line to display an Edit button in the navigation bar for this 
     view controller. 
     // self.navigationItem.rightBarButtonItem = self.editButtonItem; 
    } 

    - (void)viewDidUnload 
    { 
     [super viewDidUnload]; 
     // Release any retained subviews of the main view. 
     self.audioArray = nil; 
    } 

    - (void)viewWillAppear:(BOOL)animated 
    { 
     [super viewWillAppear:animated]; 
    } 

    - (void)viewDidAppear:(BOOL)animated 
    { 
     [super viewDidAppear:animated]; 
    } 

    - (void)viewWillDisappear:(BOOL)animated 
    { 
     [super viewWillDisappear:animated]; 
    } 

    - (void)viewDidDisappear:(BOOL)animated 
    { 
     [super viewDidDisappear:animated]; 
    } 

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
    { 
     // Return YES for supported orientations 
     return (interfaceOrientation == UIInterfaceOrientationPortrait); 
    } 

    #pragma mark - Table view data source 

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
    { 
    #warning Potentially incomplete method implementation. 
     // Return the number of sections. 
     return 1; 
    } 

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
    #warning Incomplete method implementation. 
     // Return the number of rows in the section. 
     return [self.audioArray count]; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: 
     (NSIndexPath *)indexPath 
    { 
     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle: 
     UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier] autorelease]; 
     } 

     // Configure the cell... 
     cell.textLabel.text = [self.audioArray objectAtIndex:[indexPath row]]; 

     return cell; 
    } 

    #pragma mark - Table view delegate 

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     // Navigation logic may go here. Create and push another view controller. 

     NSUInteger row = indexPath.row; 

     if (row == 0) 
     { 
    Audio1DetailViewController *audio1DetailViewController =[[Audio1DetailViewController alloc] 
    initWithNibName:@"Audio1DetailViewController" bundle:nil]; 
    audio1DetailViewController.title = @"Audio"; 
    [self.navigationController pushViewController:audio1DetailViewController animated:YES]; 
    [audio1DetailViewController release]; 

     } 

     if (row == 1) 
     { 
      //etcetera 
     } 

    } 
    - (void)dealloc{ 
     [audioArray release]; 
     [super dealloc]; 
    } 

    @end 
+0

、また[アップルドキュメントを参照してください。](http://developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPMusicPlayerController_ClassReference/Reference/Reference.html) – HDdeveloper

答えて

9

グローバルプレーヤーオブジェクトを作成することをお勧めします。今のところ、ナビゲーションコントローラ上でこのビューを押すたびに、新しいビューが作成されます。これは、あなたが以前のプレイヤーへの参照を持っていないことを意味します(それを止めることはできません)。それでは、AVAudioPlayerを一段階高く宣言してください(テーブルビューで)。ここで行を選択すると、この新しいビューのプロパティ(リンクしたもの)に割り当てられます。

ストーリーボードで作業しますか?次に、メソッドprepareForSegue:を実装する必要があります。ストーリーボード上のあなたのセグに識別子(showPlayerなど)を与え、if (segue.identifier isEqualToString:@"showPlayer")でそれをチェックします。

viewDidLoadで、audioPlayerがnilであることを確認してください。あなたの場合

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    if (audioPlayer == nil) 
    { 
     // your init (audioplayer =[[AVAudioPlayer ... 
    } 
    else 
    { 
     if (audioPlayer.isPlaying) 
     { 
      // i.e. pause the player or do other stuff 
     } 
    } 
} 

希望します。

:コードの画像を投稿しないでください。あなたの回答にコードを挿入するか、pastebin.comのようなサイトに投稿し、そのページをあなたの質問にリンクさせるだけです。これにより、他の人が簡単に反応し、コードを変更する方法を提案することが容易になります。

あなたのコメントに応えて: 関連するものは次のようになります。 AudioTableViewControllerで。時間:AudioTableViewController.mで

@property (strong, nonatomic) AVAudioPlayer *audioPlayer; 

@synthesize audioPlayer; 
... 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Navigation logic may go here. Create and push another view controller. 

    NSUInteger row = indexPath.row; 

    if (row == 0) 
    { 
     self.audio1DetailViewController =[[Audio1DetailViewController alloc] initWithNibName:@"Audio1DetailViewController" bundle:nil]; 
     self.audio1DetailViewController.title = @"Audio"; 
     self.audio1DetailViewController.audioPlayer = self.audioPlayer; 
     [self.navigationController pushViewController:self.audio1DetailViewController animated:YES]; 
     [self.audio1DetailViewController release]; 
     ... 

Audio1DetailViewController.m

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"001Fatiha" ofType:@"MP3"]]; 

    NSError *error; 

    // this is the important part: if we already have something playing, stop it! 
    if (audioPlayer != nil) 
    { 
     [audioPlayer stop]; 
    } 
    // everything else should happen as normal. 
    audioPlayer = [[AVAudioPlayer alloc] 
       initWithContentsOfURL:url 
       error:&error]; 

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
    [[AVAudioSession sharedInstance] setActive: YES error: nil]; 
+0

ねえ@ pxldlx、TNX私は試してみましたが、失敗しました。あなたが言ったことは単なる単純なことであり、それは理にかなっています。しかし、私はそれを得ていません。 IはAudio1DetailViewController.h からAudioTableViewController.hにAVAudioPlayerは、その後、私はまた、内File'sOwnerを変更AudioTableViewController.m にAudio1DetailViewController.mから全コード(ないのviewDidLoad部)に移動宣言しましたxibファイル。私は曲を再生することができますが、再生ボタンを押すのではなく、進行スライダを移動します。 私はいくつかのことを試みましたが、2日後、私はそれを断念し、すべての変更を取り消しました。 – iHilas

+0

@iHilas Mh、ok。あなたのコードを見ることなく、私はそれほどあなたを助けません。元の質問を編集していくつかのコードを追加できますか(主にイメージとして投稿したコードですが、今回はテキストでお願いします:))。ああ、一つのこと:私はあなたがそれをあまり変えなければならないとは思わない。すべてが同じままですが、audioPlayerの「所有者」をそのスーパービューに変更します(このコントローラーにはstrongというプロパティがあります)。その新しいコントローラをトラバースすると、参照用のaudioPlayerが新しいコントローラに渡されます。 –

+0

コードを追加しました – iHilas

4

あなたがこれを行う必要があり、同時に演奏2曲を停止するには:

あなたはリンゴのサンプルコードを使用することができ、オーディオを再生し、より助けのための
- (void)viewWillDisappear:(BOOL)animated 
{ 
    audioPlayer = nil; 
volumeControl = nil; 
} 

http://developer.apple.com/library/ios/#samplecode/avTouch/Introduction/Intro.html

+0

+1りんごの良いサンプル。ありがとう。 – HDdeveloper

1

驚くべきことにMPMoviePlayerControllerもコントロールとMP3プレーヤーを演じます!

self.moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:url]; 
[self.moviePlayer.view setFrame:CGRectMake(0, 0, self.videoContainer.bounds.size.width, self.videoContainer.bounds.size.height)]; 
self.moviePlayer.controlStyle=MPMovieControlStyleDefault; 
[self.videoContainer addSubview:self.moviePlayer.view]; 
[self.moviePlayer prepareToPlay]; 
[self.moviePlayer play]; 
+0

これは、コントロールでの再生に対処するための正確で最も単純な方法です。 iOS8では、Appleはあなたが表示するコントロール(airplayなど)にさらに柔軟性を加えました。 –

関連する問題